DEV Community

Pavan-Rajesh
Pavan-Rajesh

Posted on

extracting RGBA values of an Image

Here we will be using jimp which is a image processing library
and fs module in Node to extract and write the values to a text file

requiring the modules needed to extract and for storing the values
const fs = require("fs");
const { Buffer } = require("buffer");
const jimp = require("jimp");

you can install jimp as follows

npm install jimp
Enter fullscreen mode Exit fullscreen mode

after you will need to read the image which you want to extract the rgba values

here my image is named with kick.jpeg "Kick Buttowski a good cartoon right lets continue"

jimp.read("kick.jpeg").then((image) => {
  myarray = [];
  for (let i = 0; i < image.bitmap.height; i++) {
    for (let j = 0; j < image.bitmap.width; j++) {
      myarray.push([jimp.intToRGBA(image.getPixelColour(i, j))]);
    }
  }
Enter fullscreen mode Exit fullscreen mode

lets dive into the code
jimp.read returns a promise after you can apply many methods

here we will be iterating through each and every pixel and calculate rgba using intToRGBA the we will be pushing it to the array

fs.createWriteStream("rgbavalues.txt").write(JSON.stringify(myarray));

Enter fullscreen mode Exit fullscreen mode

after we will be writing the values into file called rgbvalues.txt
here is the whole code for you here we will be using streams because the file content may be large

const fs = require("fs");
const { Buffer } = require("buffer");
const jimp = require("jimp");
jimp.read("kick.jpeg").then((image) => {
  myarray = [];
  for (let i = 0; i < image.bitmap.height; i++) {
    for (let j = 0; j < image.bitmap.width; j++) {
      myarray.push([jimp.intToRGBA(image.getPixelColour(i, j))]);
    }
  }

  fs.createWriteStream("rgbavalues.txt").write(JSON.stringify(myarray));
});
Enter fullscreen mode Exit fullscreen mode

Thanks that all for today
Here is the pup for you

Image description

Top comments (0)