简体   繁体   中英

RGB array to buffer image in Node.js

I have an array consists of the RGB objects (pixel color). Example:

[
    {r: 40, g: 143, b: 54},
    {r: 86, g: 193, b: 87},
    ...
]

And I have image resolution. Example:

{
    width: 400,
    height: 300
}

How to convert this array to the Buffer in Node.js to display in a browser?

  1. Convert array of RGB objects to array of bytes.

     function RGBtoArr(rgb) { return [rgb.r, rgb.g, rgb.b]; } function flattenArray(arr) { return [].concat.apply([], arr); } var buf = new Buffer(flattenArray(arr.map(RGBtoArr))) 
  2. Encode resulting bytes to a browser-supported image format.

     var png = new Png(buf, width, height); png.encode(); 
  3. Send the resulting image to user (any of the following).
    • Embed the image in base64 into HTML.
    • Save as a png on disc and get an URL to use.
    • Send as a dynamic response on an HTTP request at a certaing URL.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM