How to generate an Image from imageData in javascr

2020-02-20 23:25发布

问题:

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.

回答1:

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


回答2:

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


回答3:

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;


回答4:

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/