• Reading time:2 mins read

How to Resize images on Server Side
I found this amazing small little image resizing code which will resize and display images quickly. All resizing i done on server side.

“The code uses PHP to resize an image (currently only jpeg). Using this method, the resized image is of much better quality than a browser-side resizing. The file size of the new downsized image is also smaller (quicker to download).

The code comes in two parts:

  • imageResize() is used to process the image
  • loadImage() inserts the image url in a simpler format”


Code

 <?php

В  В function imageResize($url, $width, $height) {

В  В  В  В  В  В  В  В  header('Content-type: image/jpeg');

В  В  В  В  В  В  В  В  list($width_orig, $height_orig) = getimagesize($url);

В  В  В  В  В  В  В  В  $ratio_orig = $width_orig/$height_orig;

В  В  В  В  В  В  В  В  if ($width/$height > $ratio_orig) {
В  В  В  В  В  В  В  В  В  $width = $height*$ratio_orig;
В  В  В  В  В  В  В  В  } else {
В  В  В  В  В  В  В  В  В  $height = $width/$ratio_orig;
В  В  В  В  В  В  В  В  }

В  В  В  В  В  В  В  В  // This resamples the image
В  В  В  В  В  В  В  В  $image_p = imagecreatetruecolor($width, $height);
В  В  В  В  В  В  В  В  $image = imagecreatefromjpeg($url);
В  В  В  В  В  В  В  В  imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

В  В  В  В  В  В  В  В  // Output the image
В  В  В  В  В  В  В  В  imagejpeg($image_p, null, 100);

В  В  В  В  }

В  В  В  В  //works with both POST and GET
В  В  В  В  $method = $_SERVER['REQUEST_METHOD'];

В  В  В  В  if ($method == 'GET') {

В  В  В  В  В  В  В  В  imageResize($_GET['url'], $_GET['w'], $_GET['h']);

В  В  В  В  В } elseif ($method == 'POST') {

В  В  В  В  В  В  imageResize($_POST['url'], $_POST['w'], $_POST['h']);
В  В  В  В  В }

В  В  В  В  // makes the process simpler
В  В  В  В  function loadImage($url, $width, $height){
В  В  В  В  В echo 'image.php?url=', urlencode($url) ,
В  В  В  В  В '&w=',$width,
В  В  В  В  В '&h=',$height;
В  В  В  В  }

?>

Usage

Above code would be in a file called image.php.

Images would be displayed like this:

<img src="<?php loadImage('image.jpg', 50, 50) ?>" alt="" />