Skip to content
Advertisement

How to generate an Image from ImageData in JavaScript?

I would like to know if there is any way to create a new Image from ImageData, which was previously obtained from a canvas element.

I’ve searched for a solution, but they all seem to be drawing the result to a canvas.

I need a way to convert an ImageData object to an Image directly, if it’s possible.

Advertisement

Answer

You can use toDataURL method in Canvas. It makes a image data as Data URI.

var canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
var ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(0, 0, 100, 100);

var img = document.createElement("img");
img.src = canvas.toDataURL("image/png");
document.body.appendChild(img);

If you want to know user’s browser supports Data URI Scheme, You can use this function.

function useSafeDataURI(success, fail) {
    var img = document.createElement("img");

    img.onerror = function () {
        fail();
    };
    img.onload = function () {
        success();
    };

    img.src = "data:image/gif;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; // insert a dot image contains 1px.
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement