JavaScript数组转换为PNG? - 客户端 [英] JavaScript array to PNG? - client side

查看:113
本文介绍了JavaScript数组转换为PNG? - 客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以将二维十六进制代码数组转换为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 http://stackoverflow.com/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? - 客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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