YemSalat
YemSalat

Reputation: 21486

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.

Upvotes: 59

Views: 89324

Answers (5)

Nikita Zlobin
Nikita Zlobin

Reputation: 15

Simple Image class is in fact HTMLImageElement, creating it from ImageData is cumbersome. Depending on application, I would propose to look at more abstract thing CanvasImageSource, for which HTMLImageElement aka Image() is implementation. For example, ImageBitmap may be created right from data, yet OffscreenCanvas could be a useful thing.

Upvotes: 0

skoll
skoll

Reputation: 2452

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;
}

Upvotes: 80

Amogh Talpallikar
Amogh Talpallikar

Reputation: 12184

A lot of modern browsers support Data URI scheme.

If you have the image data, you can set the src attribute of an img element using JavaScript.

Look at the following example: http://www.websiteoptimization.com/speed/tweak/inline-images/

Upvotes: 1

David Shim
David Shim

Reputation: 710

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.
}

Upvotes: 29

lostsource
lostsource

Reputation: 21830

Assuming this is your canvas

<canvas id='mycanvas'></canvas>

You can get a representation of your image using

var imgData = document.getElementById('mycanvas').toDataURL();

You could then put that in a regular image tag by changing its source

<img id='myimage'/>

document.getElementById('myimage').src = imgData;

Upvotes: 7

Related Questions