Creating Cropped Thumbnails With ImageMagick
So you’ve just installed ImageMagick, but how do you make your thumbnails in it? Ahhh, a very good question my friend. Why Not Use Imagick? [...]
So you’ve just installed ImageMagick, but how do you make your thumbnails in it? Ahhh, a very good question my friend.
Why Not Use Imagick?
Well like my server, not all servers have the Imagick extention for PHP installed. Also I think (personal opinion, shock) the command line is a better way to use ImageMagick. Right let’s get to it.
How Do We Use ImageMagick From The Command Line?
Well in PHP we can use the exec() function. Some servers don’t allow you to use the command, but most, like mine, just disable the use of certain functions from that function.
Anyway here is the code I use to make square cropped thumbnails.
exec("/path/to/convert -size 120x120 'input.jpg' -thumbnail 120x120^ -gravity center -extent 120x120 'output.jpg'");
Unfortunately this will only work in versions of ImageMagick from 6.3.8-3 and upwards due to the use of -thumbnail along with the carat(^) symbol. Here is what to use if you have a lower version:
convert input.jpg -resize x120 -gravity center -crop 120x120+0+0 +repage output.jpg
Of course for both of those commands you will need to change all the sizes to whatever you wish. Mine are 120px square as you can see. I also have my code only take in & output jpg files. For me this is fine, but if you want to have multiple formats you could just have pathinfo() run on the file name and use 120x120 '".$filename.".".$extention."' and it will convert any filetype to a jpg. Just remember that png or gif files with transparency will be saved with the transparent parts black.
That’s about it really. If you want any more info or if something I’ve wrote isn’t working let me know.







Discussion: 6 Comments
Thanks!
No problem.
Hey Paul, thank you for this piece of code. I was looking for something like this. However, I would also like it to take only the center portion of each image (landscape or portrait) and make a square thumbnail out of that. How can that be done?
The first code example in this tutorial should give you square thumbnails provided you have a version of IM either the same or higher than mentioned.
Sorry, I was a bit vague. I want it to ‘zoom in’ on the center of the original image and then create a square thumbnail from that. Can that be done?
Ahh, sorry. I think it can but I’m away from my computer at the minute (sending this on my iPod) and I’m afraid I don’t know the code off the top of my head. I’ll drop you another comment when I’ve had a chance to have a look at my computer.