有什么方法可以将二维十六进制代码数组转换为png图像?
Is there any way converting a 2d array of hex codes to a png image?
数组看起来像这样(只是更大了)
The arrays look like this (only much larger)
[ [ '#FF0000', '#00FF00' ], [ '#0000FF', '#000000' ] ]在此数组中,图像应如下所示
From this array, the image should look like this
如果该方法不适用于此类数组,那么它将使用哪种类型的数组?
If the method doesn't work with arrays like this, what type of array will it work with?
推荐答案如果要在不使用库的情况下呈现PNG客户端,则可以使用HTML5 Canvas.
If you want to render a PNG client-side, without libraries, you can use the HTML5 Canvas.
无论哪种方式,我都建议坚持使用一维数组,并存储图像的尺寸.它使事情变得更容易处理.
Either way, I recommend to stick to a one-dimension array, and store the image’s dimensions. It makes things a lot easier to work with.
var pixels = [ ... ], // your massive array width = 4, // width in pixels height = Math.ceil(pixels.length / width), // Create canvas canvas = document.createElement('canvas'), context = canvas.getContext('2d'), imgData = context.createImageData(width, height); canvas.height = height; canvas.width = width; // fill imgData with colors from array for(var i = 0; i < pixels.length; i++) { // Convert pixels[i] to RGB // See stackoverflow/questions/5623838/rgb-to-hex-and-hex-to-rgb imgData[i] = r; imgData[i + 1] = g; imgData[i + 2] = b; imgData[i + 3] = 255; // Alpha channel } // put data to context at (0, 0) context.putImageData(imgData, 0, 0); // output image var img = new Image(); img.src = canvas.toDataURL('image/png'); // add image to body (or whatever you want to do) document.body.appendChild(img);或者,如果您不能依靠像这样的相对较新的功能,或者只是发现这项工作太多,则可以寻求汤姆的答案:)
Alternatively, if you can’t rely on a relatively new feature like this, or simply find this too much work, you can go for Tom’s answer :)
更多推荐
JavaScript数组转换为PNG?
发布评论