Home ยป Resize images with PHP on file upload using ImageMagick to dynamically generate thumbnails and different image sizes

Resize images with PHP on file upload using ImageMagick to dynamically generate thumbnails and different image sizes


This is an example of a function I wrote for a client to handle image uploads and dynamically resize the original image to 500×500 and generate different image sizes (thumbnails, etc.) with PHP using ImageMagick.

If you don’t have have ImageMagick installed, or are unsure if you do, you’ll want to install it first. If you’re on CentOS or a RHEL based linux OS you can do so with the following:

This example is fairly particular to the situation I was coding so the image paths, accepted file types, image dimensions, and other variables should be modified to suit your needs.

Also, keep in mind that this code was written for a system that was completely locked down so I recommend using escshellarg() or escshellcmd() or other forms of user input sanitization before using exec() like I am below. It’s up to you to secure this and prevent users from executing nasty stuff on your filesystem.

Obviously you’ll need to change “logo” to whatever the name of your file input is, change the $upload_path variable to the upload path on your server, and modify the $sizes array and image dimensions to your liking.

Also note that I prefer to have logo-[dimension].png (always using .png as the extension) because in this example I needed a specific naming convention. You can change this to use whatever image naming convention you want. Don’t forget to add enctype=”multipart/form-data” to your form tag either ๐Ÿ˜‰ – Let me know if you have any questions.

Leave a Reply

Your email address will not be published. Required fields are marked *