简体   繁体   English

如何在 asp.net C# 中以图像字节转换 HTML5 画布图像?

[英]How to convert HTML5 canvas image in Image bytes in asp.net C#?

I captured an image in canvas with the help of following code (using external webcam).我借助以下代码(使用外部网络摄像头)在画布中捕获了一张图像。 Then, I tried to save that canvas image in a folder.然后,我尝试将该画布图像保存在一个文件夹中。 But, I was unable to open that saved image as it was not in proper format.但是,我无法打开该保存的图像,因为它的格式不正确。

So, how to get Image Bytes from canvas Image in order to store image in folder, or directly save canvas image in folder?那么,如何从画布图像中获取图像字节以便将图像存储在文件夹中,或者直接将画布图像保存在文件夹中?

MyCam.aspx我的相机.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="myCam.aspx.cs" Inherits="html_Web_Cam_test.simpleWebCam.myCam" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">    <title></title> </head>

<body>    <form id="form1" runat="server">    <div style="border:solid">

<video id="video" width="400" height="300"></video>

<%--onserverclick="savePhoto"--%>
<input runat="server" type="button" id="startBtn" value="Start WebCam" onclick="startWebcam();"/>
<input runat="server" type="button" id="stopBtn" value="Stop WebCam" onclick="stopWebcam();"/>
<input runat="server" type="button" id="capture" value="Take Photo"/>

<asp:Button runat="server" ID="saveBtn" Text="Save Photo" OnClick="saveBtn_Click"/>

<canvas id="canvas" width="400" height="300" controls autoplay></canvas>

<img runat="server" src="" id="img1" width="300" height="250" alt="no Image"/>

<asp:Label runat="server" ID="lbl1"></asp:Label>

<asp:HiddenField runat="server" ID="hidden1"/>
</div>    </form>

<%--<script src="takePhoto.js"></script>--%>
</body>

<script>
var video;
var webcamStream;
var video = document.getElementById('video'),
canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
vendorUrl = window.URL || window.webkitURL;

navigator.getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;

navigator.getMedia({
    video: true,
    audio: false
}, function (stream) {
    video.src = vendorUrl.createObjectURL(stream);
    video.play();
}, function (error) {
});

document.getElementById('capture').addEventListener('click', function() {
    context.drawImage(video, 0, 0, 400, 300);
    //convertCanvasToImage(canvas);

    var image = document.getElementById('img1');
    image.src = canvas.toDataURL("image/png");

    var dataURL = canvas.toDataURL("image/png");

    var vrrr = canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, '');
    var hiddenControl = '<%= hidden1.ClientID %>';
    document.getElementById(hiddenControl).value = vrrr;

    return vrrr;
});

function startWebcam() {
    if (navigator.getUserMedia) {
        navigator.getUserMedia({
            video: true,
            audio: false
        }, function (localMediaStream) {
            video = document.querySelector('video');
            video.src = window.URL.createObjectURL(localMediaStream);
            webcamStream = localMediaStream;
        }, function (err) {
            console.log("The following error occured: " + err);
        });
    } else {
        console.log("getUserMedia not supported");
    }
}

function stopWebcam() {
    webcamStream.stop();
}
</script> </html>

MyCam.aspx.cs我的相机.aspx.cs

private static byte[] ConvertHexToBytes(string hex)
{
    byte[] bytes = new byte[hex.Length / 2];
    for (int i = 0; i < hex.Length; i += 2)
    {
        bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
    }
    return bytes;
}

protected void saveBtn_Click(object sender, EventArgs e)
{
    using (StreamReader reader = new StreamReader(Request.InputStream))
    {
        string str1 = Server.UrlEncode(reader.ReadToEnd());

        string imageName = "Image_" + DateTime.Now.ToString("dd-MM-yy hh-mm-ss");
        string imagePath = string.Format("~/SavedPics/{0}.png", imageName);

        File.WriteAllBytes(Server.MapPath(imagePath), ConvertHexToBytes(str1));

        byte[] visImageBytes = ConvertHexToBytes(str1);
    }
}

You shouldn't get the image as dataURL, get it as a blob/binary file and then upload it using FormData and a bit of ajax (xhr / fetch ).您不应该将图像作为 dataURL 获取,将其作为 blob/二进制文件获取,然后使用FormData和一些 ajax (xhr / fetch ) 上传它。 Since it not possible to attach a file to a file input [ 1 ]由于无法将文件附加到文件输入[ 1 ]

canvas.toBlob(function(blob){
  var fd = new FormData()
  fd.append('image', blob, 'image.png')
  // fetch(uploadUrl, {method: 'post', body: fd})
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM