JavaScript数组转换为PNG? - 客户端
有没有办法将二进制代码转换为PNG图像?JavaScript数组转换为PNG? - 客户端
所述阵列看起来像这样(仅大得多)
[
[
'#FF0000',
'#00FF00'
],
[
'#0000FF',
'#000000'
]
]
从该阵列中,图像应该是这样的
如果该方法不与像阵列工作这是什么类型的数组?
如果你想呈现一个PNG客户端,没有图书馆,你可以使用HTML5画布。
无论哪种方式,我建议坚持一维数组,并存储图像的尺寸。它使事情变得更容易。
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);
另外,如果你不能依赖于这样一个相对较新的功能,或者干脆觉得这工作太多了,你可以去汤姆的答案:)
代码中有三个拼写错误:'putImagedata' - >'putImageData','toDataUR'L是'canvas'的函数而不是'context',在循环中需要操作'imgData.data'只是'imgData'。 – johjoh 2017-02-16 17:25:50
PNGlib看起来很有帮助。你将不得不创建一个类似的例子一个循环:
var p = new PNGlib(200, 200, 256);
for (var x = 0; x < 2; x++)
for (var y = 0; y < 2; y++)
p.buffer[p.index(x, y)] = p.color(/* your colour */);
document.write('<img src="data:image/png;base64,' + p.getBase64() + '">');
这很难给出与您所提供的信息更具体的例子,但我认为这是你追求的。显然你必须改变不同数组的x和y限制。
你可以RGB值的数组画上HTML5 canvas object,然后开始使用.toDataURL()
帆布方法画布内容:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<script>
"use strict";
// Here's the image data we want to draw:
var data = [
["#FF0000", "#00FF00"],
["#FFFF00", "#0000FF"]
];
// First, we need to create a canvas with the same dimensions as the image data:
var canvas = document.createElement("canvas");
canvas.height = data.length;
canvas.width = data[0].length;
//canvas.style.visibility = "hidden";
document.body.appendChild(canvas);
// Now that we have canvas to work with, we need to draw the image data into it:
var ctx = canvas.getContext("2d");
for (var y = 0; y < data.length; ++y) {
for (var x = 0; x < data[y].length; ++x) {
ctx.fillStyle = data[y][x];
ctx.fillRect(x, y, 1, 1);
}
}
// Finally, we get the image data using the .toDataURL() canvas method:
console.log(canvas.toDataURL("image/png"));
</script>
</body>
</html>
好多了! – Cerbrus 2015-02-09 08:55:31
...并且将这样的PNG图像是什么样子?那些颜色数组代表什么? – CodingIntrigue 2015-02-09 08:36:12
第一维是x,第二维是y – Kerndog73 2015-02-09 08:42:10
分享你的研究可以帮助每个人。告诉我们你试过了什么,以及它为什么不符合你的需求。这表明你已经花时间去尝试帮助自己,它使我们避免重申明显的答案,最重要的是它可以帮助你得到更具体和相关的答案!另请参阅[如何问](http://stackoverflow.com/questions/how-to-ask)。就目前而言,这个问题太广泛了,可以解决这个问题的答案太多了。 – Cerbrus 2015-02-09 08:42:47