PHP GD library is more than enough for image processing, it supports numerous image formats and offers enough capabilities. But sometimes enough is not enough, sometimes we want to try out ImageMagick, just for the sake of performance, code clarity or just to explore more functionality. So today instead of using PHP GD, we are going to create an image upload and resize script using ImageMagick (PHP) and jQuery.
As you can see GD library is already included in PHP since 4.3. But ImageMagick is not always available for use, most web hosts do offer ImageMagick to their clients, but some don’t! So it’s better to confirm with yours whether they offer ImageMagick on their server. But if you only want to test it on localhost (Windows), you must install ImageMagick, you can follow these installation steps.
HTML file input box
Let’s create a basic HTML file input box for image upload. We just want to upload and resize image without refreshing the page, so we will be using jQuery Ajax to facilitate that later. Input field will be hidden here initially, as we will trigger click using jQuery which will trigger “open file” dialog box.
Upload page using HTML5 FileAPI & jQuery
As I mention earlier, user click on text inside upload-wrapper DIV element will open “file open” dialog box, which allows user to choose and upload files. Technique is simple; just using jQuery trigger().
Once user selects a file, we can validate file format before uploading it to server using FileAPI
And then using FormData object and jQuery, we can send file to server as Ajax request. Code below is simple example of posting file to server, but please remember to check Browser compatibility as old browsers do not support XMLHttpRequest 2 and FileAPI features.
Playing with ImageMagick
ImageMagick is very simple to use. It will resize, distort, crop, explode, blur and do many more on fly. There are various different things you can do with your image, and surprisingly you have less code to write and will look very neat.
Resize Image : For example, here’s how simple it is to resize your image using ImageMagick in PHP.
Resize Animated GIF : Some people face problem with Animated GIF in PHP GD, but with ImageMagick it’s not a problem. To resize animated GIF file, you can simply follow code below. It will resize your GIF file but keeping your animation intact.
PHP Resize Page
Let’s combine these two examples and create our PHP image resizing page. This will allow users to upload regular images as well as animated GIF files.
That’s all you need to create an Ajax based image uploader that uses PHP ImageMagick features to resize normal images as well as GIF animated images. If you want to resize images using regular PHP GD, read my another article here.
You can also checkout this step by step video created by Webucator below :