PHP: Resizing image using php gd librarby

Hello everyone,

Lets learn about php gd library a bit. This article will include about how to re-size the image into a required height and width. Below example will read an image from remote address according to the provided image url. Then re-size the image into a 180x180 size. Just follow the code comment to understand what actually happening.


## resizing image using php gd library

## Get the image from a provided link,
## You can read the image from a local file too
$large_image = imagecreatefromjpeg( 'https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiDtZMOuy2YgZbC2C-aufSbPb2kF5TKh8RYc8yARb_P3tDgogivzxvAjkH6yy6h2cQodA3tmOPTWu49ATsT2PXyn5i4bKzrgmJeAKdYlxYoXmiPveX6AOaoCpW1cBtWAaZMtGMFBxU-KOaK/s320/EasyPHP+curl.JPG' );

## provided the dimension of the new smaller image
$x = 180;
$y = 180;

## create a black blank image with provided dimension
$small_image = imagecreatetruecolor($x,$y);

## Just copy the larger image into the smaller image using resamplimg
imagecopyresampled($small_image,$large_image,0,0,0,0,$x,$y,imagesx($large_image),imagesy($large_image));

## Its always better to free the memory if you don't need this
imagedestroy($large_image);

## Lets save the image file into your local directory
$file = 'image.jpg';
imagejpeg($small_image, $file);

## If you want to output this into your browser, that case
## Just ignore the file name.
# imagejpeg($small_image);

## Once again, free the memeory
imagedestroy($small_image);

The function imagecreatefromjpeg() uses the fopen() to read from remote location. Some website may not allow to read the image. That case you can use Curl. Using the curl, just read the remote data into a variable, and using the function imagecreatefromstring() just make the $large_image. Rest of the things is as it is.
$large_image = imagecreatefromstring($curl_output);


Post your thought if anything goes wrong... or if you find this helpful for you.

Comments

Absulit said…
Thanks this is the best code :)