Canvas to img with src blob
Asked Answered
A

2

6

I'm creating a PNG file from a canvas, but before I want to display the canvas as an img element, using a blob as the src of the img. What I tried so far:

canvas = document.getElementById("canvas");
//Get data from canvas
img_b64 = canvas.toDataURL('image/png');
//Create PNG
png = img_b64.split(',')[1];
//Create new img
img = document.createElement("img");
img.src = img_b64;
//Append img to document
//Save png

This works, but instead of img_b64 I want a blob to be the src of the img, like this:

//Create blob from new PNG
blob = new Blob([window.atob(png)], { type: 'image/png', encoding: 'utf-8' });
//Create new img with blob as src
img = document.createElement("img");
img.src = URL.createObjectURL(blob);
//Append img to document
//Save png

The above code only shows me an empty img. Is there a way to do this or do I have to create the png file first and afterwards create a blob for it?

Alecalecia answered 11/12, 2014 at 8:48 Comment(1)
looking at blob = new Blob([window.atob(png)]..., how is png in that statement defined?Catie
A
6

I just found an solution using the answer to this question: Convert Data URI to File then append to FormData. Using the dataURItoBlob function my code is:

canvas = document.getElementById("canvas");
//Get data from canvas
img_b64 = canvas.toDataURL('image/png');
//Create blob from DataURL
blob = dataURItoBlob(img_b64)
img = document.createElement("img");
img.src = URL.createObjectURL(blob);
//Insert image

dataURItoBlob function:

function dataURItoBlob(dataURI) {
    // convert base64/URLEncoded data component to raw binary data held in a string
    var byteString;
    if (dataURI.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(dataURI.split(',')[1]);
    else
        byteString = unescape(dataURI.split(',')[1]);

    // separate out the mime component
    var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];

    // write the bytes of the string to a typed array
    var ia = new Uint8Array(byteString.length);
    for (var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }

    return new Blob([ia], {type:mimeString});
}
Alecalecia answered 11/12, 2014 at 9:37 Comment(1)
Just wanted to drop in and say that in the meantime <canvas> got a toBlob() method that might be helpful.Gezira
P
3

With toBlob this should be easy to solve from IE>=10.

  const img = document.createElement("img");
  canvas.toBlob((blob) => {
    img.src =  URL.createObjectURL(blob);
  });
Properly answered 13/6, 2020 at 22:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.