Web Programming: Resize an Image (on the fly) & Keep its Aspect Ratio using PHP and GD

This is a PHP Class useful if you need to resize images keeping their aspect ratio, using the GD Library. The new height is calculated proportionally to the new width’s size and reverse. For instance you have an image with the following dimensions: width – 1000, height – 800. Its thumbnail with a width of 250 will have the height of 200 (the ratio is kept).

Here’s the class (I will explain you how it works below):

resize.image.class.php

001.<?php
002./*
003.---------------------------------------------------------------------
004.Credits: Bit Repository
005.
007.---------------------------------------------------------------------
008.*/
009.class Resize_Image {
010.
011.var $image_to_resize;
012.var $new_width;
013.var $new_height;
014.var $ratio;
015.var $new_image_name;
016.var $save_folder;
017.
018.function resize()
019.{
020.if(!file_exists($this->image_to_resize))
021.{
022. exit("File ".$this->image_to_resize." does not exist.");
023.}
024.
025.$info = GetImageSize($this->image_to_resize);
026.
027.if(empty($info))
028.{
029. exit("The file ".$this->image_to_resize." doesn't seem to be an image.");
030.}
031.
032.$width = $info[0];
033.$height = $info[1];
034.$mime = $info['mime'];
035.
036./*
037.Keep Aspect Ratio?
038.
039.Improved, thanks to Larry
040.*/
041.
042.if($this->ratio)
043.{
044.// if preserving the ratio, only new width or new height
045.// is used in the computation. if both
046.// are set, use width
047.
048.if (isset($this->new_width))
049.{
050.$factor = (float)$this->new_width / (float)$width;
051.$this->new_height = $factor * $height;
052.}
053.else if (isset($this->new_height))
054.{
055.$factor = (float)$this->new_height / (float)$height;
056.$this->new_width = $factor * $width;
057.}
058.else
059.exit(”neither new height or new width has been set”);
060.}
061.
062.// What sort of image?
063.
064.$type = substr(strrchr($mime, '/'), 1);
065.
066.switch ($type)
067.{
068.case 'jpeg':
069. $image_create_func = 'ImageCreateFromJPEG';
070. $image_save_func = 'ImageJPEG';
071. $new_image_ext = 'jpg';
072. break;
073.
074.case 'png':
075. $image_create_func = 'ImageCreateFromPNG';
076. $image_save_func = 'ImagePNG';
077. $new_image_ext = 'png';
078. break;
079.
080.case 'bmp':
081. $image_create_func = 'ImageCreateFromBMP';
082. $image_save_func = 'ImageBMP';
083. $new_image_ext = 'bmp';
084. break;
085.
086.case 'gif':
087. $image_create_func = 'ImageCreateFromGIF';
088. $image_save_func = 'ImageGIF';
089. $new_image_ext = 'gif';
090. break;
091.
092.case 'vnd.wap.wbmp':
093. $image_create_func = 'ImageCreateFromWBMP';
094. $image_save_func = 'ImageWBMP';
095. $new_image_ext = 'bmp';
096. break;
097.
098.case 'xbm':
099. $image_create_func = 'ImageCreateFromXBM';
100. $image_save_func = 'ImageXBM';
101. $new_image_ext = 'xbm';
102. break;
103.
104.default:
105. $image_create_func = 'ImageCreateFromJPEG';
106. $image_save_func = 'ImageJPEG';
107. $new_image_ext = 'jpg';
108.}
109.
110. // New Image
111. $image_c = ImageCreateTrueColor($this->new_width, $this->new_height);
112.
113. $new_image = $image_create_func($this->image_to_resize);
114.
115. ImageCopyResampled($image_c, $new_image, 0, 0, 0, 0, $this->new_width, $this->new_height, $width, $height);
116.
117. if($this->save_folder)
118. {
119. if($this->new_image_name)
120. {
121. $new_name = $this->new_image_name.'.'.$new_image_ext;
122. }
123. else
124. {
125. $new_name = $this->new_thumb_name( basename($this->image_to_resize) ).'_resized.'.$new_image_ext;
126. }
127.
128. $save_path = $this->save_folder.$new_name;
129. }
130. else
131. {
132. /* Show the image without saving it to a folder */
133. header("Content-Type: ".$mime);
134.
135. $image_save_func($image_c);
136.
137. $save_path = '';
138. }
139.
140. $process = $image_save_func($image_c, $save_path);
141.
142. return array('result' => $process, 'new_file_path' => $save_path);
143.
144. }
145.
146. function new_thumb_name($filename)
147. {
148. $string = trim($filename);
149. $string = strtolower($string);
150. $string = trim(ereg_replace("[^ A-Za-z0-9_]", " ", $string));
151. $string = ereg_replace("[ tnr]+", "_", $string);
152. $string = str_replace(" ", '_', $string);
153. $string = ereg_replace("[ _]+", "_", $string);
154.
155. return $string;
156. }
157.}
158.?>

Variables Info$image_to_resize – Here we set the full path (i.e. /home/www.mysite.com/public_html/images/myimage.jpg) to the image we wish to resize. If the image is in the same folder with the class, then you can just set the filename as the path (i.e. mywallpaper.jpg).

The $new_width & $new_height are the new dimensions for the resized image.

$ratio – Do you wish to keep the image’s ratio aspect after resize? If it’s set to true it will calculate the new dimensions based on the new width (if it’s bigger than the height) or the new height (if it’s bigger than width).

$new_image_name – It’s used to set a name for the new resized image. If it’s not set a name will be assigned automatically.

$save_folder – The path to the folder where the new image will be saved. Make sure it’s writable (0777). It no folder is set the new image will show in the browser without being saved.
Here’s an example of how you can use this class:

01.<?php
02.include 'resize.image.class.php';
03.
04.$image = new Resize_Image;
05.
06.$image->new_width = 200;
07.$image->new_height = 200;
08.
09.$image->image_to_resize = "/home/mysite.com/public_html/images/sunset_wallpaper.jpg"; // Full Path to the file
10.
11.$image->ratio = true; // Keep Aspect Ratio?
12.
13.// Name of the new image (optional) - If it's not set a new will be added automatically
14.
15.$image->new_image_name = 'sunset_wallpaper_thumbnail';
16.
17./* Path where the new image should be saved. If it's not set the script will output the image without saving it */
18.
19.$image->save_folder = 'thumbs/';
20.
21.$process = $image->resize();
22.
23.if($process['result'] && $image->save_folder)
24.{
25.echo 'The new image ('.$process['new_file_path'].') has been saved.';
26.}
27.?>

How to invoke this class to generate thumbnails in a HTML page?

This class has an advantage: you can resize images ‘on the fly’ with it. This way you don’t have to necessarily save the resized image on the server. You can just output it. Here’s how you can call this class from a HTML page without using any PHP code in it:

demo.html

01.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
02.<html>
03. <head>
04. <title> Show Resized Image </title>
05. <meta name="Author" content="Bit Repository">
06. <meta name="Keywords" content="src, image, resize, on the fly">
07. <meta name="Description" content="Display a resized image">
08. </head>
09. <body>
10. <img src="resize_image.php?image=sunset.jpg&new_width=200&new_height=200">
11. </body>
12.</html>

As you can see, the resize_image.php script is called. Some info is needed to make the resize: original image (‘image’), a width (‘new_width’) and a height (‘new_height’). In many cases, if the ‘ratio aspect’ is enabled, you can specify only one measurement. The new dimensions will be calculated based on whether you choose: width or height. Here’s the resize_image.php script:

resize_image.php

01.<?php
02.set_time_limit(10000);
03.
04.error_reporting(E_ALL ^ E_NOTICE);
05.
06.include 'resize.image.class.php';
07.
08.$resize_image = new Resize_Image;
09.
10.// Folder where the (original) images are located with trailing slash at the end
11.$images_dir = 'images/';
12.
13.// Image to resize
14.$image = $_GET['image'];
15.
16./* Some validation */
17.if(!@file_exists($images_dir.$image))
18.{
19.exit('The requested image does not exist.');
20.}
21.
22.// Get the new with & height
23.$new_width = (int)$_GET['new_width'];
24.$new_height = (int)$_GET['new_height'];
25.
26.$resize_image->new_width = $new_width;
27.$resize_image->new_height = $new_height;
28.
29.$resize_image->image_to_resize = $images_dir.$image; // Full Path to the file
30.
31.$resize_image->ratio = true; // Keep aspect ratio
32.
33.$process = $resize_image->resize(); // Output image
34.?>

source: http://www.bitrepository.com/resize-an-image-keeping-its-aspect-ratio-using-php-and-gd.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s