How to Resize images on Server Side

How to Resize images on Server Side

2 49620

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”


   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) ,


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="" />



  1. Nice. I was using also a very similar technique. Its cool because you don’t need to store thumbnails, and you can generate them on the fly. The problem is that it’s slow, specially when you have many images to be resized on the same page (i.e on an ecommerce site). Some say ImageMagick is quicker, I havent tried.

  2. I dont know much but I personally feel somethings about any development, either its a website or c++. Thanks for this site.

Leave a Reply