Rob
Rob

Reputation: 53

How do I convert a text file of RGB values into a png file?

Problem statement:

Using ImageMagick, I can do:

convert a.png a.txt

which gives me:

# ImageMagick pixel enumeration: 297,239,255,srgba
0,0: (255,255,255,1)  #FFFFFF  white
1,0: (255,255,255,1)  #FFFFFF  white
2,0: (255,255,255,1)  #FFFFFF  white
3,0: (255,255,255,1)  #FFFFFF  white
...

I also want to be able to go from a text file back to a png. How can I do this? I'd be happy to use any linux command line tools, programming language libraries etc.

Context:

I have parsed the pixel values of the original image into q (the language I'm using) using the ImageMagick tool. I then performed a transformation on them and now want to save the image corresponding to the new pixel values. Using q I can easily save the rgb values in any text format required.

Upvotes: 0

Views: 6312

Answers (1)

Mark Setchell
Mark Setchell

Reputation: 207465

It works the same both ways:

# Image to text
convert image.png image.txt

# Text to image
convert image.txt andBack.png

It is probably better to write a NetPBM file though - so PGM (P5) if greyscale, and PPM (P6) if colour. The format is very simple and described here.

There are several variants known as P1 through P6. P1 is rarely used and just mono and inefficient. P2 is greyscale and ASCII (human-readable) and P5 is the same but binary and therefore more compact. P3 is colour and ASCII (human-readable) and P6 is the same but binary and therefore more compact.

Here is a 4x4 white (255) rectangle with a 1-pixel wide mid-grey (127) border making a 6x6 PGM:

P2
6 6
255
127 127 127 127 127 127 
127 255 255 255 255 127 
127 255 255 255 255 127 
127 255 255 255 255 127 
127 255 255 255 255 127 
127 127 127 127 127 127

enter image description here

Here is a colour PPM which corresponds to a 3x1 row of RGB pixels:

P3
3 1
255
255 0 0
0 255 0
0 0 255

enter image description here

You can then convert this back to PNG with ImageMagick

convert image.ppm image.png
convert image.pgm image.png

You could also just write the raw binary bytes in the order RGB, RGB, RGB to a file and then convert it to PNG with ImageMagick like this:

convert -size 1024x768 RGB:data.bin image.png

or for grayscale:

convert -size 1024x768 GRAY:data.bin image.png

and while that would be marginally smaller, it is no longer self-contained like a PGM/PPM file and means you have to carry around the size separately to be able to get your data back, so I would go for the PGM/PPM version for the sake of 3 tiny lines of header.


Note that you can also do all the above conversions between NetPBM and PNG formats with the much lighter-weight NetPBM tools (or libvips or GIMP, or others) rather than ImageMagick.

For example, with NetPBM, to convert PPM to PNG:

pnmtopng a.ppm > result.png

Upvotes: 4

Related Questions