How to create and store a thumbnail in php

Here I will show you guys how to create a thumbnail from a larger image file ( .jpg file)

You create a new .php file, and enter this function:

1
2
3
4
5
6
7
8
9
10
11
<?php
function thumbnail($file, $size, $save_as) {
 list($width, $height) = getimagesize($file) ;
 $modwidth = $width * $size;
 $modheight = $height * $size;
 $tn = imagecreatetruecolor($modwidth, $modheight) ;
 $image = imagecreatefromjpeg($file) ;
 imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;
 imagejpeg($tn, $save_as, 100) ;
 }
?>

then you can call the function like this:

1
2
3
<?php
   thumbnail('original_image.jpg', '0.60', 'new_image.jpg');
?>

The last part calls the function, and tells it to create a thumbnail from the “original_image.jpg”, with 0.6 the size of the original, and store the new image as “new_image.jpg” in the same folder as the script.

Some of the code in the function is explained in this post.

Simple :)

3 Responses to “How to create and store a thumbnail in php”

  1. ehellabe Says:

    Creating thumbnails in PHP with GD works fine for small images, but the memory limit is often to short when we are talking about larger. Thats may be a problem, so its best to be aware of it. A solution is to use server-side (PHP) for small images, and client-side (Javascript (Ajax), Java ..) for the smaller ones.

    Einar :)

  2. ehellabe Says:

    Uhh… I meant:

    A solution is to use server-side (PHP) for small images, and client-side (Javascript (Ajax), Java ..) for the larger ones.

  3. Ratman87 Says:

    Yes I know :) I should probably write a guide on how to do it in ajax too :) But for small avatars in forums and such, this works fine :)
    Ratman87

Leave a Reply


To prove that you're not a bot, enter this code
Anti-Spam Image

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>