How to generate an Image from imageData in javascript?

YemSalat picture YemSalat · Nov 16, 2012 · Viewed 67.2k times · Source

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. So basically I need a way to convert an ImageData object to Image directly, if its possible.

Answer

skoll picture skoll · Dec 19, 2016

None of the previous answers provide an answer to the question as it was presented in the subject - getting an Image from ImageData. So here's a solution.

function imagedata_to_image(imagedata) {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    canvas.width = imagedata.width;
    canvas.height = imagedata.height;
    ctx.putImageData(imagedata, 0, 0);

    var image = new Image();
    image.src = canvas.toDataURL();
    return image;
}