Simplified Image Resizing with PHP

Share this article

If you’re anything like me, you’re probably lazy (and if you’re not, give yourself a pat on the back!).
Recently, as I built a Website to show off a range of products, I realized that not only was I going to want to use the same product image over and over again, but I was going to want to use that same image at different sizes throughout the site! I thought to myself, “I don’t feel like having 4,000 different thumbnails on my server for each product, and I don’t want to have the image look all jacked-up and distorted if I hard code the image width and height in my HTML”. I know what you’re thinking. Why couldn’t I just use something like ImageMagik? In most cases, I would use ImageMagik so that I could have a regular version and a thumbnail version of each image. But in this particular case, I wanted to be able to display various sizes of the same image, without having 4,000 different thumbnails sitting around taking up space. So how did I do it? Well, I improvised. I knew these things:
  • I wanted one image per product.
  • I wanted the size of the altered image to keep its aspect ratio, no matter whether it was landscape or portrait.
  • I wanted one script to do all of this dynamically.
So, with the knowledge I’d gained using PHP almost on a daily basis, I sat down and started figuring out a function to achieve these goals. I am by no means a PHP guru — in fact, I taught myself the language sometime in the summer of 2002, so by most standards, I’m still a newbie. But I thought I could create a script that would do exactly what I wanted…
Getting Started
Let’s say you have a great line of socks that you want to sell through your site. Well, you’re proud of these fantastic socks and want people to see as much of them as possible: on the product views page, on the search page, on the listing page, etc. But this doesn’t mean that you have to use the default image size each time, nor risk the quality of the image being degraded when it is stretched or crunched into a space. Some socks are longer than others and so you might have the image sizes ranging from 200×400 up to 600×750 pixels. To begin writing the function, we have to declare it as such… Then we have to throw in our attributes. We want to restrict our image, so we have to let the function know the dimensions to which we want to restrict it, and we have to know what the original image size is to begin with (we’ll get to that part in a second).
<?php 
function imageResize($width, $height, $target) {

//takes the larger size of the width and height and applies the
formula accordingly...this is so this script will work
dynamically with any size image

if ($width > $height) {
$percentage = ($target / $width);
} else {
$percentage = ($target / $height);
}

//gets the new value and applies the percentage, then rounds the value
$width = round($width * $percentage);
$height = round($height * $percentage);

//returns the new sizes in html image tag format...this is so you
can plug this function inside an image tag and just get the

return "width="$width" height="$height"";

}

 

?>
Before we take our new function on a test drive, we need to get the width and height of the image that we want to display. There is a magical command in PHP called getimagesize(). This command, used properly, will return the image width, height, type, and even the width and height in HTML image tag format (width=”x” height=”y”).
$mysock = getimagesize("images/sock001.jpg");
Now, $mysock is an array that holds vital information about the particular image we want to display. In index 0, we have the width ($mysock[0]), and in index 1, we have the height ($mysock[1]
). That’s really all we need, in order to get what we want done. Want to see the function… well, function? Here we go!
The Function in Action
Let’s say you want to display a list of your beautiful socks, but you want room on the page to show them neatly in a row, and to do that they cannot be larger than 150 pixels tall or wide.
<?php 

//get the image size of the picture and load it into an array
$mysock = getimagesize("images/sock001.jpg");

?>

<!-using a standard html image tag, where you would have the
width and height, insert your new imageResize() function with
the correct attributes -->

 

<img src="images/sock001.jpg" <?php imageResize($mysock[0],
$mysock[1], 150); ?>>
That’s it! Now, no matter what the original file size, it will be restricted to no more than 150 pixels in width or height (or whatever you specify). Now, you may think “This sounds too good to be true. Is there any circumstance where using this technique could prove disastrous?” Actually, there is. Keep in mind that you aren’t changing the file’s original size. That same 200×400, 50 KB picture you uploaded only moments ago is still 200×400, 50 KB. This script only changes height and width attribute in HTML, so that your original picture conforms to the height and width you think will look best on your Web page. Having said that, if you have a page that lists 50-something products, the page will display the way you want it to, but uses will have to download all 50 of those 50 KB pictures, which could take some time. So I’d have to recommend this technique in situations where you’re only showing a few pictures at a time.

Frequently Asked Questions (FAQs) on Image Resizing in PHP

What are the basic steps to resize an image in PHP?

Resizing an image in PHP involves a few steps. First, you need to load the image using the imagecreatefromjpeg() function for JPEG images. This function returns an image resource identifier representing the image obtained from the given filename. Next, you need to get the original image’s width and height using the imagesx() and imagesy() functions. Then, you can calculate the new dimensions of the image. After that, you create a new true color image with the new dimensions using the imagecreatetruecolor() function. Finally, you can copy and resize part of an image with resampling using the imagecopyresampled() function and output the image.

How can I maintain the aspect ratio when resizing an image in PHP?

Maintaining the aspect ratio of an image when resizing is important to prevent distortion. You can maintain the aspect ratio by calculating the ratio of the original width to the new width or the original height to the new height. Then, use the smaller of these two ratios to calculate the new width and height. This ensures that the new dimensions will not exceed the original dimensions, thus maintaining the aspect ratio.

Can I resize PNG and GIF images in PHP?

Yes, you can resize PNG and GIF images in PHP. The process is similar to resizing JPEG images. However, instead of using the imagecreatefromjpeg() function, you would use the imagecreatefrompng() function for PNG images and the imagecreatefromgif() function for GIF images.

How can I improve the quality of a resized image in PHP?

You can improve the quality of a resized image in PHP by using the imagecopyresampled() function instead of the imagecopyresized() function. The imagecopyresampled() function performs pixel interpolation, which results in better image quality compared to the imagecopyresized() function.

How can I save a resized image to a file in PHP?

After resizing an image, you can save it to a file using the imagejpeg() function for JPEG images, the imagepng() function for PNG images, or the imagegif() function for GIF images. These functions take two parameters: the image resource identifier and the path to the file where you want to save the image.

Can I resize an image without losing its transparency in PHP?

Yes, you can resize an image without losing its transparency in PHP. To do this, you need to use the imagesavealpha() function to set the flag to save full alpha channel information, and the imagealphablending() function to turn off alpha blending.

How can I resize an image to a specific width or height in PHP?

To resize an image to a specific width or height, you can calculate the new dimensions based on the desired width or height while maintaining the aspect ratio. Then, use these new dimensions to create a new true color image and copy and resize the original image.

Can I resize an image directly from a URL in PHP?

Yes, you can resize an image directly from a URL in PHP. You can use the file_get_contents() function to get the image data from the URL, and then create an image resource from the data using the imagecreatefromstring() function.

How can I handle errors when resizing an image in PHP?

You can handle errors when resizing an image in PHP by using the try-catch block. In the try block, you perform the image resizing operations. If an error occurs, an exception is thrown and caught in the catch block, where you can handle the error appropriately.

Can I resize multiple images at once in PHP?

Yes, you can resize multiple images at once in PHP. You can do this by putting the image resizing code in a loop that iterates over an array of image filenames. For each filename, you load the image, resize it, and save it to a file.

Greg KnoxGreg Knox
View Author

Greg started his pursuit of knowledge in PHP and MySQL in the Summer of 2002. Currently, NokX is involved in freelance work under the name NokX, but is expanding and joining forces to create a new identity that has yet to be named.

Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week