45

我想知道是否有任何方法可以从之前从画布元素获得的 imageData 创建新图像?

我已经寻找解决方案,但他们似乎都将结果绘制到画布上。因此,如果可能的话,基本上我需要一种将 ImageData 对象直接转换为 Image 的方法。

4

4 回答 4

62

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;
}
于 2016-12-19T19:17:58.210 回答
25

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.
}
于 2012-11-16T12:49:22.207 回答
7

假设这是你的画布

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

您可以使用

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

然后,您可以通过更改其来源将其放入常规图像标签中

<img id='myimage'/>

document.getElementById('myimage').src = imgData;
于 2012-11-16T12:45:00.130 回答
1

许多现代浏览器都支持数据 URI 方案。

如果您有图像数据,则可以使用 JavaScript 设置 img 元素的 src 属性。

看下面的例子: http ://www.websiteoptimization.com/speed/tweak/inline-images/

于 2012-11-16T12:45:01.630 回答