Wednesday, January 27, 2010

How to resize an image in PHP

How to resize an image in PHP?

Following example shows you how to resize an image in PHP.

In some cases you may need to resize images in your web site. As an example create a profile picture from a large file. Using this PHP script you can resize an image to given width and height.
This can use when you create thumbnail images.

In this php code current date time is used to save the resized image.
You may need to create a directory named "images" in your application and another directory in it called "resized"
to save resized images.

Functions that are needed to resize an image using PHP

PHP function
 file_exists ( string $filename )
 Checks whether a file exists.
getimagesize ( string $filename [, array &$imageinfo ] )
 determine the size of any given image file.
imagecreatefromgif ( string $filename )
 Create an image identifier using the image obtained from the given filename.
imagecreatefromjpeg ( string $filename )
 Create an image identifier using the image obtained from the given filename.
imagecreatefrompng ( string $filename )
 Create an image identifier using the image obtained from the given filename.
imagesx ( resource $image )
 Get the width of the given image resource.
 imagesy ( resource $image )
 Get the height of the given image resource.
 imagecreatetruecolor ( int $width , int $height )
 Create a new true color image of the specified size.
 imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
 Copies a rectangular portion of one image to another image
 imagegif ( resource $image [, string $filename ] )
 Creates the GIF file in filename from the image image.
 imagejpeg ( resource $image [, string $filename [, int $quality ]] )
 Creates a JPEG file from the given image.
 imagepng ( resource $image [, string $filename [, int $quality [, int $filters ]]] )
Outputs or saves a PNG image from the given image .

Bookmark and Share

1. Example code for resize an image using PHP.

PHP Code
class ImageResize{
private $image;

private $imageType;

private $imageHeight;

private $imageWidth;

function loadImageFile($image_path){




case "image/gif":{




case "image/jpeg":{




case "image/png":{





die("Incompatible file type");






die("File does not exists");



function resizeImage($width,$height,$resizedImageName=''){








case 1:{//gif



case 2:{//jpg



case 3:{//png






How to use above image resize class in your php code?

$resize=new ImageResize();




Useful  PHP Codes/Programs

 »   How to create random validation image in PHP
 »   How to get extension of a file using PHP
 »   How to upload and encrypt file in PHP
 »   How to upload files in PHP
 »   How to create arrays in PHP
 »   How to create thumbnail images in PHP
 »   How to connect MySQL Database in PHP

©-Copyright By Duminda Chamara 
JavaScript Validation