Grow your CSS skills. Land your dream job.

Last updated on:

Server Side Image Resizer

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:

  • imageResizer() is used to process the image
  • loadimage() inserts the image url in a simpler format
<?php

   function imageResizer($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) ?>"

Comments

  1. Permalink to comment#

    YAY!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1 im going nuts my snippets made it u dont how happy i am :)

    Check out my site

  2. Permalink to comment#

    on thing chris u should show who made the snippets

  3. Peter Dubrovski
    Permalink to comment#

    Whats about GIF and PNG?

    Get/Post
    $method = $_SERVER['REQUEST_METHOD'];

    Should go with

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

  4. Hi! How would you format the link so that it includes the required alternate tag for the image?

  5. I am trying to link to images in specific directories but it encodes URL so images come back black.
    Is there a way to modify script to prevent encoding URL?

    • Paul Garcia
      Permalink to comment#

      Tom,
      I think (not sure) your problem is not ENCODEDING stuff.
      I think problems is URL invocation:
      Depends of PHP installation your URLs has to be /root/ directory based not domain (http://www…..) related, means:
      if you try to use a image in a directory “inside” same php installation (means image is in the same server as the resize script) you have to use something like this:
      /root/www/domain/htpdocs/images/yourimage.jpg instead:

      http://www.doamin.com/images/yourimage.jpg

      to find out your “real” path use: PHP supervariable
      $_SERVER["DOCUMENT_ROOT"]

      $myPath = $_SERVER["DOCUMENT_ROOT"];
      $myImage = $mypath . “/images/myimagen.jpg”;

      or better check this trick (that works perfect for us in all or scripts):

      if (!file_exists($urlImage)) $urlImage=str_ireplace(‘http://’.$_SERVER["HTTP_HOST"],$_SERVER["DOCUMENT_ROOT"],$urlImage);

      Got it? it reemplace “http://www.domain.com” with your “real” path IF “don’t” find the image (means internal image)

      Hope this help you.

  6. Paul Garcia
    Permalink to comment#

    Be aware of the high CPU RESOURCES used by functions like imagecreatetruecolor(), imagecreatefromjpeg(), imagecopyresampled() and other PHP image’s related functions.
    We used a PHP resize approcach in a high traffic website and we have to remove it because CPU SERVER RESOURCES were going crazy a couple of times a crash occurs (a resize process for every single user) we opted for a different approach (a WordPress like) at the moment of upload we create different sizes to be served (WordPress do that when a image is used in their posts)

  7. This would work perfectly with a client-side service like picturePolyfill. Give it a try!

  8. Marcel
    Permalink to comment#

    How do you add support for png?

Leave a Comment

Posting Code

Markdown is supported in the comment area, so you can write inline code in backticks like `this` or multiline blocks of code in in triple backtick fences like ```this```. You don't need to escape code in backticks, Markdown does that for you.

Sadly, it's kind of broken. WordPress only accepts a subset of HTML in comments, which makes sense, because certainly some HTML can't be allowed, like <script> tags. But this stripping happens before the comment is processed by Markdown (via Jetpack). It seems to me that would be reversed, because after Markdown processes code in backticks, it's escaped, thus safe. If you think you can fix this issue, get in touch!

If you need to make sure the code (typically HTML) you post absolutely posts correctly, escape it and put it within <pre><code> tags.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".