If you are a web developer then you definitely have been faced with this little thingy. Let’s say you want to do dynamic resizing of images for a project of yours. All you need is an extension for PHP called GD. With that you are given many possibilities on image handling and manipulation, among others resizing. There, though,is a small problem you need to face. Let’s take it one step at a time.
Here is an image we want to resize:
Below is a small resizing script:
$source = imagecreatefromjpeg('tree.jpg');//opening image assuming you have an image called tree.jpg on the same folder of the script $source_width = imagesx($source); $source_height = imagesy($source); $ratio = $source_width / $source_height;//the ration of the image which is a VERY good idea to preserve $dest_width = 300;//width of the resized image $dest_height = $dest_width / $ratio;//height of the resized image preserving the ratio $destination = imagecreate($dest_width, $dest_height);//creating a new image imagecopyresized($destination, $source, 0, 0, 0, 0, $dest_width, $dest_height, $source_width, $source_height);//resizing the image by actually copying a part (here the whole image but you can use a part) to the new image we created //rendering the image to the browser header('Content-Type: image/jpeg'); imagejpeg($destination); //a good idea to free up some space especially if this script is part of a bigger one imagedestroy($source); imagedestroy($destination);
As you can see, it’s not rocket science. All we do is open the image, create a new canvas, copy a part (or whole) of the image and put it resized there using imagecopyresized. After running the script, here is the result:
Wops! As you can see, something, not so desirable, has happened! Although the image is resized preserving it’s initial ratio the colors are all messed up! It’s scrambled! To fix this small con all we need to do is change the way we create the new image (on line 7) using function “imagecreatetruecolor” instead of the simple “imagecreate”. This way, we avoid color scrambling. If you change the above code according to that and run it again here is the new image you will get:
Perfect! Congratulations on a perfect resize! Now start creating your php image gallery 😉
If you find any errors, have any suggestions or bugs please leave a comment!