Search code examples
bashimagemagickimagemagick-convert

Trying to use Imagemagick to convert an RGB image into a list of hex codes, each for every pixel


As the title states, I'm attempting to make a script which reads an image, doesn't matter the resolution, and converts the image into a list of hex codes. For example, an 8x8 PNG Image with alternating white and black pixels would be converted into this:

FFFFFF
000000
FFFFFF
000000
FFFFFF
000000

And so on. I've tried the following so far:

convert $name.png -compress none pnm:-

However, the above code returned just regular numbers instead of hex values. Here's an example:

205 0 0 205 0 0 205 0 0 205 0 0 205 0 0 205 0 0 224 160 0 224 160 0 224 160 0 

What went wrong here, and what changes would I make to it to make it output hex codes?


Solution

  • This works for me:

    convert yourimage.png txt:- | tail -n +2 | sed -n 's/^.*#\([0-9A-Fa-f]*\).*$/\1/p'
    

    See http://www.imagemagick.org/Usage/files/#txt