How to store ImageMagick output into Bash variable (and then use it)?

2k views Asked by At

I use ImageMagick and need to do conditional resize of images.

For that I store results of the identify tool into variables.

$infile='test.jpg'
width=$(identify -ping -format %w $infile)
height=$(identify -ping -format %h $infile)

But before resizing I want to do some transformations that change image size: -trim and -shave. So I need to calculate image size in between of trimming and resizing. And I'd like to do the trim operation only once to make a little optimization.

So, I'd like:

  1. to do trim and shave
  2. store [binary] result in a variable (for example: $data)
  3. pass $data variable value as input to identify tool and store its result for conditional resizing
  4. pass $data to convert tool and finish processing

Something like this:

data=$(convert logo: -shave 1x1 gif:-)
width=$(echo $data | identify -ping -format %w gif:-)
echo $data | convert -resize "$width"

But echo doesn't work as needed.

P. S. convert and identify are tools from ImageMagick suite

1

There are 1 answers

6
emcconville On BEST ANSWER

Bash can not store blobs of data that may contain NULL terminating characters. But you can convert the data to base64, and use ImageMagick's fd: protocol.

# Store base64-ed image in `data'
data=$(convert logo: -shave 1x1 gif:- | base64)
# Pass ASCII data through decoding, and pipe to stdin file descriptor
width=$(base64 --decode <<< $data | identify -ping -format %w fd:0)
base64 --decode <<< $data | convert -resize "$width" -