How to Serve Resized Images with PHP

  1. Home
  2. Knowledge Base
  3. WordPress Plugins
  4. How to Serve Resized Images with PHP

There are many reasons we use PHP to serve images on sites including: resizing, watermarking, skewing, server-caching, etc. This will cover the basics of serving and resizing an image with PHP. This technique will work with JPG, JPEG, GIF PNG image types. Well cover more advanced image manipulation techniques in later posts.

The first line of code calls the functions.phtml include we defined in our PHP Image Manipulation Functions post, change the /path/to/include/ to your path. The second line $_GETs the image file from the URL we want to manipulate, and assigns it to the $img1 variable. The third line checks if this requested image is a file, otherwise we use a generic No Photo image to prevent no image from displaying. The fourth line checks if the requested file is an image and surrounds the remaining code with the if statement.

Next part of the code gets the MIME type of the image file and calls the proper image header based on that MIME type.

With the following code we determine the final images width and height. Based on the presence of $_GET[a] variable in the URL used to represent aspect, our code: makes a smaller image with the aspect ratio kept intact, otherwise it makes a thumbnail with equal width and height starting from the images center. For thumbnails a width of 100 pixels is default, if we do not specify a width, with a max of 178 pixels. For non-thumbnails (with aspect preserved) a default width of 300 pixels is set with a maximum of 588 pixels. These numbers can be changed, we just set them to work within our sites layout.

We then determine the original images width and height.

With the following code we determine the final images width and height. Our code makes thumbnails with equal with and height from an images center, or a smaller image with the aspect ratio kept intact all based on the presence of $_GET[a] variable in the URL.

Finally we re-sample then print the image with PHP.

 


Putting it all together we arrive at the following code, we named our PHP file thumb.php since its primary role is to make thumbnails for the site.

Now we simply call the image in a generic HTML image tag. Be sure to use the alt portion of the image tag so that if the image generation fails text still appears, not to mention this will aid in SEO. Below we are calling an image that has a max 200pixel width/height, keeping the aspect ratio, using an image named uwcmc.jpg for our United Way of Cape May County client.

Below we are calling an image without specifying width or aspect ration, again using an image named uwcmc.jpg.

 

Was this article helpful?

Related Articles

Leave a Reply