gpt4 book ai didi

JavaScript数组到PNG? - 客户端

转载 作者:行者123 更新时间:2023-12-01 08:28:09 26 4
gpt4 key购买 nike

有没有办法将二维十六进制代码数组转换为 png 图像?

数组看起来像这样(只是更大)

[
[
'#FF0000',
'#00FF00'
],
[
'#0000FF',
'#000000'
]
]

从这个数组中,图像应该是这样的

enter image description here

如果该方法不适用于这样的数组,它将适用于哪种类型的数组?

最佳答案

如果您想在没有库的情况下呈现 PNG 客户端,您可以使用 HTML5 Canvas。

无论哪种方式,我都建议坚持使用一维数组,并存储图像的尺寸。它使事情变得更容易使用。

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

或者,如果您不能依赖这样一个相对较新的功能,或者只是觉得这工作量太大,您可以寻求 Tom 的答案 :)

关于JavaScript数组到PNG? - 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28405619/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com