How to Resize images on Server Side

Tutorials

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

01 <?php
02    function imageResize($url$width$height) {
03                 header('Content-type: image/jpeg');
04                 list($width_orig$height_orig) = getimagesize($url);
05                 $ratio_orig $width_orig/$height_orig;
06                 if ($width/$height $ratio_orig) {
07                   $width $height*$ratio_orig;
08                 else {
09                   $height $width/$ratio_orig;
10                 }
11                 // This resamples the image
12                 $image_p = imagecreatetruecolor($width$height);
13                 $image = imagecreatefromjpeg($url);
14                 imagecopyresampled($image_p$image, 0, 0, 0, 0, $width$height$width_orig$height_orig);
15                 // Output the image
16                 imagejpeg($image_p, null, 100);
17         }
18         //works with both POST and GET
19         $method $_SERVER['REQUEST_METHOD'];
20         if ($method == 'GET') {
21                 imageResize($_GET['url'], $_GET['w'], $_GET['h']);
22          elseif ($method == 'POST') {
23             imageResize($_POST['url'], $_POST['w'], $_POST['h']);
24          }
25         // makes the process simpler
26         function loadImage($url$width$height){
27          echo 'image.php?url=', urlencode($url) ,
28          '&w=',$width,
29          '&h=',$height;
30         }
31 ?>

Usage

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

Images would be displayed like this:

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