在javascript和Html5中从Array创建图像 [英] Creating image from Array in javascript and Html5

查看:115
本文介绍了在javascript和Html5中从Array创建图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码。我在javascript中创建了imageData 2D数组。在我将所有像素放入此数组后,我想创建图像并将这些值放入图像中。

Here is my code. I created imageData 2D array in javascript. After I put all pixels into the this array, I want to create image and put these values into the image.

    var imageData = new Array(width);

    var image = new Image;

for (var i = 0; i < width; i++) {
    imageData[i] = new Array(height);
}

    image.src = imageData; //Here is the problem. I want to do that. 


推荐答案

要从数组创建图像,您可以执行以下操作:

To create an image from array you can do this:

var width = 400,
    height = 400,
    buffer = new Uint8ClampedArray(width * height * 4); // have enough bytes

* 4 最后代表RGBA,我们需要与canvas兼容。

The * 4 at the end represent RGBA which we need to be compatible with canvas.

用一些数据填充缓冲区,例如:

Fill the buffer with some data, for example:

for(var y = 0; y < height; y++) {
    for(var x = 0; x < width; x++) {
        var pos = (y * width + x) * 4; // position in buffer based on x and y
        buffer[pos  ] = ...;           // some R value [0, 255]
        buffer[pos+1] = ...;           // some G value
        buffer[pos+2] = ...;           // some B value
        buffer[pos+3] = 255;           // set alpha channel
    }
}

填充时使用缓冲区画布来源:

When filled use the buffer as source for canvas:

// create off-screen canvas element
var canvas = document.createElement('canvas'),
    ctx = canvas.getContext('2d');

canvas.width = width;
canvas.height = height;

// create imageData object
var idata = ctx.createImageData(width, height);

// set our buffer as source
idata.data.set(buffer);

// update canvas with new data
ctx.putImageData(idata, 0, 0);

请注意,您可以使用imageData缓冲区(此处为:idata.data)而不是创建自己的缓冲区。如果你使用例如浮点值或从其他来源获取缓冲区,那么创建自己的实际上非常有用 - 设置缓冲区如上所述将为你剪切和舍入值。

Note that you could use the imageData buffer (here: idata.data) instead of creating your own. Creating your own is really only useful if you use for example floating point values or get the buffer from some other source - setting the buffer as above will take care of clipping and rounding the values for you though.

现在,自定义数组中的数据被复制到画布缓冲区。下一步是创建一个图像文件:

Now the data in your custom array is copied to the canvas buffer. Next step is to create an image file:

var dataUri = canvas.toDataURL(); // produces a PNG file

现在你可以使用data-uri作为图像的来源: / p>

Now you can use the data-uri as source for an image:

image.onload = imageLoaded;       // optional callback function
image.src = dataUri

这篇关于在javascript和Html5中从Array创建图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆