Monthly Archives: August 2017

Resize an animated gif using imagemagik

This is a nice easy one liner:

convert original.gif -coalesce -repage 300x175+0-25 -layers optimize resized.gif

-coalesce expands the image into a series of frames while -repage will re-compress them into one image again. No need for temp files or cleanup!  The 300×175 specifies the new size for the image, while +0-25 specifies where to pull the segment of the canvas from in the old image.  My goal here was to extract x 300×175 animated gif from a 400×230 original.

Update: I also needed to pad the image with more pixels to the left & right, so it would have a particular aspect ratio, and fill the added pixels with a specific color.  To get the color from the top left pixel from the original image I used this:

convert 'original.gif[0]' -colorspace rgb -crop 1x1+0+0 text:

Then, used this to pad the image I’d resized previously:

convert reiszed.gif -coalesce -repage 0 -colorspace rgb -background "#1541BA" -extent 700x175-200+0 padded.gif

This resulted in a 700×175 animated GIF, which is the correct aspect I was going for.  Then this command to resize it to 800×200, which I needed to match the required spec:

convert padded.gif -coalesce -repage 0 -resize 800x200 800x200.gif


Removing empty entries in a PHP array

I’m working on some PHP code right now, and I need to split a URI path and recombine it with some changes.  However, I ran into an issue using explode.  This is what I had:

$parts = explode('/',$path);

This worked as expected, unless the URI ended with a ‘/’, in which case I ended up with an empty string as the last item.  Also, if it started with a ‘/’ then I’d get an empty string at the start.  I decided to fix this using array_filter with the default predicate, like so:

$parts = array_filter(explode('/',$path));

Job done, right? Nope! Turns out array_filter doesn’t reindex anything, so my array ended up with no [0] entry, and $parts[count($parts)-1] didn’t return the last entry anymore.  I needed to rebuild the array with new indexes.  Solved it by using array_values like so:

$parts = array_values(array_filter(explode('/',$path)));

If it was mission critical, maybe it would be more efficient to create an iterator that loops over the exploded array and appends any non-zero length strings to a new array, but I’ll save that for another day.