Some useful convert (ImageMagick) commands

I must sometimes modify images and PDF documents in PHP. Prepare them to display after user upload, prepare for database, fix dimensions or many other things. Of course we can use native PHP functions, but it’s very slow. Better option is to use external libs like convert (ImageMagick) and Ghostscript.  Today I have some useful convert commands – it’s “list to remember” for me, but maybe also you will find someting nice? This post is short, because I paste only commands and very short description.

Fix image orientation

Phone images can have wrong image orientation – an example is photo form iPhone: good on computer, but 90 degree rotated after upload and display in user browser. You will don’ see it in image browsers but it can be very frustating. But.. how detect rotation? It’s simple, you can just remove orientation flag:

Remove transarency

We don’t want to use alpha channel when we create thumbnails, so it’s nice idea to remove transparency:

Force output file format

Convert always tries detect output format based on name, but sometimes it’s wrong or we just don’t want to use extensions. We can still forcr output format and save file with custom name:

Create thumbnails

I mentioned about thumbnails. It’s also good example. We can easily create thumbnails with max-size using convert:

Rotation (and conditional rotation)

We can rotate images using degrees, but also use conditional rotate – only when height is higher than width or vice versa:

Image resizing

Sometimes we want to resize image (with or without keep aspect ratio):

Set gravity

Hard to exmplain, but it’s very important option – with gravity option we can set postion of other elements on image (text, other images, etc):

Expand workspace:

We can also just expand image “workspace”. It’s good option with gravity. There is an example. Let’s say we have 200x250px image. The command will make 640×480 px file with this small image in center.

Summarize: use many options

Last example: we want convert image to PDF file, we also want to make it as as big as possible on A4 page – we must rotate that image if needed and also use white background. Hard? Not!