JavaScript数组转换为PNG?

编程入门 行业动态 更新时间:2024-10-27 18:29:40
本文介绍了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 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?

本文发布于:2023-07-27 05:25:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1220598.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   转换为   JavaScript   PNG

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!