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( '' );

## 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

## Its always better to free the memory if you don't need this

## 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

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 :)