Page 1 of 1

extract hex code and append to file name

Posted: 2018-01-13T19:29:51-07:00
by alexmak01
Hi, I'm a first time user trying to solve a problem.

I have a directory full of single color images to be used as color swatches for a web site. There are thousands of them. I need to extract the #hex code from each image and then save it with the hex code appended to the end of the image.
For example an imagecalled dt_black.gif has a hex code of #232323, i would like to have the program extract the hex code from the image and rename ,make a copy of the image in a new directory, appending the extracted color code to the end, so the new file would be called called dt_black-#232323.gif

If that is possible, please advise on how it can be done.

Thank you

Alex

Re: extract hex code and append to file name

Posted: 2018-01-13T20:38:18-07:00
by fmw42
It can be done it either IM 6 or IM 7. Please always provide your IM version and platform! %[hex:...] requires IM 6.9.8.9 or higher or IM 7.0.5-10 or higher. Alternately, for older systems, one has to extract the hex color using a second line of code from txt: listing to the terminal into a variable.

For IM 6:

Code: Select all

convert dt_black.gif -set filename:fn "%t_#%[hex:u.p{0,0}].%e" "%[filename:fn]"
creates a new image named: dt_black_#232323.gif

For IM 7, replace convert with magick.

For many files, you would have to write a script loop over each image in some directory.

The above assumes the hex color you want is at the top left pixel of the image.

NOTE that IM will always read and write the image. So if using a lossy compressed format such as JPG, you may lose quality and the color may change slightly.

Re: extract hex code and append to file name

Posted: 2018-01-13T21:07:52-07:00
by fmw42
Alternately, if you do not want to read and write the file and just change the name, then if using Unix (Linux, Mac OSX, etc), you can use Imagemagick to find the old name and create a new name. Then use the OS to rename the file. In unix, that is the mv command.

Code: Select all

oldfile="dt_black.gif"
newfile=`convert "$oldfile" -format "%t_#%[hex:u.p{0,0}].%e" info:`
mv $oldfile $newfile
For many files, you would have to write a script loop over each image in some directory. And that depends upon your OS.