ParadigmTheGreat
ParadigmTheGreat

Reputation: 21

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?

Upvotes: 1

Views: 1036

Answers (2)

fmw42
fmw42

Reputation: 53164

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

Upvotes: 2

Mark Setchell
Mark Setchell

Reputation: 207748

You could use ImageMagick to decode the file to raw RGB values and xxd to group them and display in hex:

convert yourImage.png rgb:- | xxd -g3

I use -g3 to group into threes for RGB files, and if there is an alpha/transparency layer:

convert yourImage.png rgba:- | xxd -g4

Other switches you might like to use with xxd would be:

xxd -g3 -c15    # 15 bytes per line, good if you have 5 pixels of 3 bytes each, so hex lines match image scanlines

xxd -ps         # continuous output without offsets at start of lines

Upvotes: 2

Related Questions