简体   繁体   中英

ASP.NET C# How do I pass canvas image to controller as Bitmap

I have the following javascript that sends the canvas image on my View to the controller in the form of a string. But I would like to convert the string into a Bitmap format. How can I do so?

    document.getElementById('save').addEventListener('click', function () {
    var image = document.getElementById("canvas").toDataURL("image/png");
    image = image.replace('data:image/png;base64,', '');

    $.ajax({
        type: 'POST',
        url: "Attendance/Decode",
        data: '{ "imageData" : "' + image + '" }',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (msg) {
            alert("Done, Picture Sent.");
        }
    });

});

Controller Method:

public ActionResult Decode(string imageData)
{
   //Convert imageData to Bitmap
}

Is there any other way to send the canvas image as a Bitmap to the controller?

If you're receiving a URI or Base64, you can use BitmapImage() to convert it to bitmap.

Uri:

 BitmapImage bitmapImage = new BitmapImage(url);

Base64String:

BitmapImage bitmapImage = new BitmapImage();
byte[] byteBuffer = Convert.FromBase64String(base64String);
MemoryStream memoryStream = new MemoryStream(byteBuffer);
memoryStream.Position = 0;
bitmapImage.SetSource(memoryStream);
memoryStream.Close();
memoryStream = null;
byteBuffer = null;

Hope it helps!

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