Wednesday, March 11, 2009

PHP: Resizing image using php gd librarby


Share at Facebook

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( 'http://2.bp.blogspot.com/_jGEuU1zFjq8/R_ZZdbfEJhI/AAAAAAAAAKE/pbZeAbu8_Xg/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.




1 comment:

Absulit said...

Thanks this is the best code :)