tollin jose
tollin jose

Reputation: 955

How to convert 24 bit RGB array into an image?

My program result is giving 24 bit RGB data. It is very difficult verify my result by looking into the array of 24 bit data.

If there is any easy method to convert this array to an image, I can easily verify my result. Expecting your help for the same. Please.

Example: 4x3 Resolution Image, I have following data as text file.

110000001100000011000000 110000001100000011111111 110000001100000011111111 110000001100000011111111 110000001100000011111111 110000001100000011111111 110000001100000011000000 110000001100000011111111 110000001100000011111111 110000001100000011111111 110000001100000011111111 110000001100000011111111

Upvotes: 0

Views: 1391

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207465

I had a look at this and it is pretty ugly but works - I think. I use awk to convert the ones and zeroes into straight numbers, and lay them out in a PPM format file which is about the simplest file format you can get from the NetPBM suite documentation here.

So, for a 4x3 image with RGB and 255 as the maximum pixel intensity, your file will need to look like this:

P3     # header saying PPM format
4 3    # 4x3 pixels
255    # max value per pixel is 255
192    # Red value of top left pixel
192    # Green value of top left pixel
192    # Blue vaue of top left pixel
...
...

So, I convert your file like this

#!/bin/bash
tr ' ' '\n' < file | awk '
   function bintxt2num(str){
      result=0;
      this=1;
      for(i=8;i>0;i--){
         if(substr(str,i,1)=="1")result += this
         this*=2
      }
      print result
   }
   BEGIN{ printf "P3\n4 3\n255\n"}
   {
      R=substr($0,1,8);  bintxt2num(R);
      G=substr($0,9,8);  bintxt2num(G);
      B=substr($0,17,8); bintxt2num(B);
   }' | convert ppm:- -scale 5000% result.png

And at the end, I use the ImageMagick tool convert to convert the PPM file output from awk into a PNG file called result.png and scale it up to a decent size while I am at it.

It looks like this:

enter image description here

In case I have made a silly mistake somewhere in my awk, your PPM file comes out looking like this:

P3
4 3
255
192
192
192
192
192
255
192
192
255
192
192
255
192
192
255
192
192
255
192
192
192
192
192
255
192
192
255
192
192
255
192
192
255
192
192
255

If you object to, or cannot install ImageMagick for some reason, you can always use the original NetPBM binaries and run ppm2tiff or ppm2jpeg to do the conversion from PPM to TIFF or JPEG. See here.

Upvotes: 3

Related Questions