简体   繁体   中英

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

<%@ 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

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 ). Since it not possible to attach a file to a file input [ 1 ]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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