Generating JPG/GIF/PNG thumbnails in PHP using imagegif, imagejpeg, imagepng

Don't you just adore the sim­plic­ity of PHP? It is a cake walk to cre­ate thumb­nails in PHP, with­out any plu­g­ins like imagemag­ick or NetPBM, and it is super fast too. Here's the sim­ple code.

Don't you just adore the sim­plic­ity of PHP! It is a cake walk to cre­ate thumb­nails in PHP, with­out any plu­g­ins like imagemag­ick or NetPBM, and it is super fast too. Here's the sim­ple code.

The fol­low­ing code takes a "source image" from a "source path" and makes a thumb­nail out of it, plac­ing the thumb­nailed image into a "thumb path." It is fairly straight­for­ward so I won't waste time explain­ing stuff. Post a com­ment below if you have any ques­tions or problems.

- Ele­ments that you'll prob­a­bly have to edit are high­lighted in red
 – Com­ments are in green

Make sure the path for thumb­nails is write­able, the image­jpeg func­tion takes care of writ­ing by itself, you don't need to fwrite etc.

<?

$sour­cePath = 'images/'; // Path of orig­i­nal image
$sourceUrl = 'http://domain.com/images/';
$source­Name = 'test.jpg'; // Name of orig­i­nal image
$thumb­Path = $sour­cePath . 'thumbs/'; // Write­able thumb path
$thum­bUrl = $sourceUrl . 'thumbs/';
$thumb­Name = "test_thumb.jpg"; // Tip: Name dynam­i­cally
$thumb­Width = 60; // Intended dimen­sion of thumb

// Beyond this point is sim­ply code.
$sour­ceIm­age = image­cre­ate­fromjpeg("$sourcePath/$sourceName");
$sourceWidth = imagesx($sour­ceIm­age);
$source­Height = imagesy($sour­ceIm­age);

$tar­ge­tIm­age = image­cre­ate($thumbWidth,$thumbWidth);
image­copy­re­sized($targetImage,$sourceImage,0,0,0,0,$thumbWidth,
$thumbWidth,imagesx($sourceImage),imagesy($sourceImage));
image­jpeg($tar­ge­tIm­age, "$thumbPath/$thumbName");

// By now, the thumb­nail is copied into the $thumb­path
// as the file name spec­i­fied in $thumb­Name, so dis­play

echo "<img src='$thumbUrl$thumbName' alt=''>";

?>

This above exam­ple is for JPEG for­mat. Replace all occurences of "jpeg" in the above code with "gif" and you're good to go for GIF files! Sim­i­larly, you can edit the "jpeg" to "png" and you're good to go. For instance, replace "imagejpeg" with "imagegif" or "imagepng".

Even­tu­ally, you can also cob­ble together some code to fig­ure out the file type of a $sourceImage dynam­i­cally (from a direc­tory on the server for instance) and apply the appro­pri­ate func­tions. This is just an exam­ple to give you an idea!

Just FYI, my setup on the server is as follows:

  1. Root HTTP folder: /home/domain/public_html/
  2. Images folder: /home/domain/public_html/images/
    This becomes our $sourcePath because this is where the orig­i­nal image comes from.
  3. Thumbs folder: /home/domain/public_html/images/thumbs/ (this folder is CHMODed 744, and is our $thumbPath)
  • Cine

    This requires GD installed on the server, and not all hosts have that either.

  • Shaik Yes­dani

    Hai ,

    This is a nice site .
    Gen­er­at­ing JPG/GIF/PNG thumb­nails in PHP using imagegif, image­jpeg, imagepng the exam­ple code is very good one.

    Hope this site will help lots of devel­oper like me

    thank u.

  • ake

    imagegif is not working!

  • http://sniptools.com snip­tools

    Ake, please elab­o­rate when you write mes­sages on this site. What do you mean is not work­ing — the code is result­ing in errors, or does the PHP ver­sion you use not sup­port imagegif? It does work, for mil­lions of people.

  • Sean

    I do belive that gif sup­port was pulled in later ver­sions of, some­thing to do with licenc­ing restric­tions on this format.

  • Sean

    I do belive that gif sup­port was pulled in later ver­sions of GD, some­thing to do with licenc­ing restric­tions on this format.

  • Wes

    Imagegif is only work­ing in GD2 or higher if im right. Check what ver­sion u got with ur host or ur server.

  • gx

    http://my2.php.net/manual/en/function.imagegif.php

    [quote]
    In case you are won­der­ing (I know I've been) GD sup­port for GIFs will not re-appear until the patent GIF expires world-wide on July 7th, 2004. Though the patent has expired in the U.S. it hasn't in Europe.[/quote]

  • Mihai

    I found that the thumb­nail gen­er­ated has VERY washed out col­ors (JPEG). I am dis­s­a­pointed with the poor qual­ity of the image. If some­one has a solu­tion for this please email me if any­one has some time. mihai323@hotmail.com

    Thanks.

  • Vince

    Relat­ing to the above comment…

    Use image­cre­atetrue­color() NOT image­cre­ate()
    AND
    Use image­copy­re­sam­pled() NOT imagecopyresized()

    This tuto­r­ial seems to be for GD

  • Vince

    that last line of my above com­ments is sup­posed to say:
    The com­ments seems to be for GD ver­sion 2 or less

  • Moon­dog

    The lat­est builds of GD2 now have gif sup­port again. If your server is not allow­ing it ask them to upgrade to the lat­est ver­sion of GD2. Believe me it vastly improves over GD1.

  • Parag

    Is there any way to cre­ate thumb­nails with­out using
    GD, IM, NETBPM.

  • jae­Sun

    as stated above, requires GD1. GIF as far as i know isnt sup­ported due to licens­ing, even though the license expired last year. but even so, GD1 is very poor qual­ity (gallery.menalto.com has an exam­ple of it). bet­ter to use ImageMag­ick or NetPBM, or even GD2.

  • dave

    thanks for the tip about using image­copy­re­sam­pled() instead of image­copy­re­sized(). It pro­duces a much nicer, softer thumb­nail :)

  • shaik sha­ja­han

    good site indeed.It helps to find out good tricks as well.

  • soban [BG]

    (Sorry for my Eng­lish)
    A lit­tle improved function -

    <?php
    func­tion thum­b­gen­er­a­tor ( $image, $save­or­show, $qual­ity, $thumb­size , $save­name){ // v.1 by Soban
    $han­dle = @imagecreatefromjpeg( $image );
    $x = imagesx ( $han­dle ); // Image Orig­i­nal Width
    $y = imagesy ( $han­dle ); // Image Orig­i­nal Height

    // Cal­cu­lat­ing whitch side is larger
    if ( $x > $y ){
    $max = $x;
    $min = $y;
    }
    if ( $x <= $y ){
    $max = $y;
    $min = $x;
    }
    $rate = $max / $thumb­size; // Thumb­nail Ratio
    $final_x = $x / $rate;
    $final_y = $y / $rate;
    if( $final_x > $x ) {
    $final_x = $x;
    $final_y = $y;
    }
    $final_x = ceil ( $final_x ); // Thub­nail Width
    $final_y = ceil ( $final_y ); // Thub­nail Height
    $black_picture = image­cre­atetrue­color ( $final_x, $final_y ); // Gen­er­at­ing blank image for thumb­nail
    image­fill ( $black_picture, 0, 0, image­col­oral­lo­cate ( $black_picture , 255, 255, 255 ) );
    image­copy­re­sam­pled ( $black_picture, $han­dle, 0, 0, 0, 0, $final_x, $final_y, $x, $y );
    imagestring ($black_picture, 1, $final_x-4, $final_y-8, ".", image­col­oral­lo­cate ( $black_picture, 0, 0, 0 ) );
    if ( $save­or­show == 'show' ) { header ( 'Content-type: image/jpeg' ); image­jpeg ( $black_picture, '', $qual­ity); }
    if ( $save­or­show == 'save' ) image­jpeg ( $black_picture, $save­name, $qual­ity);
    if ( $save­or­show == 'save&show' ) { header ( 'Content-type: image/jpeg' ); image­jpeg ( $black_picture, '', $qual­ity); image­jpeg ( $black_picture, $save­name, $qual­ity); }
    imagede­stroy ( $han­dle );
    imagede­stroy ( $black_picture );
    }
    thum­b­gen­er­a­tor ('images/030.jpg', 'save', 10, 100, 'thumbs/newimage1.jpg');
    thum­b­gen­er­a­tor ('images/030.jpg', 'save', 20, 100, 'thumbs/newimage2.jpg');
    thum­b­gen­er­a­tor ('images/030.jpg', 'save', 30, 100, 'thumbs/newimage3.jpg');
    thum­b­gen­er­a­tor ('images/030.jpg', 'save', 40, 100, 'thumbs/newimage4.jpg');
    thum­b­gen­er­a­tor ('images/030.jpg', 'save', 50, 100, 'thumbs/newimage5.jpg');
    thum­b­gen­er­a­tor ('images/030.jpg', 'save', 60, 100, 'thumbs/newimage6.jpg');
    thum­b­gen­er­a­tor ('images/030.jpg', 'save', 70, 100, 'thumbs/newimage7.jpg');
    thum­b­gen­er­a­tor ('images/030.jpg', 'save', 80, 100, 'thumbs/newimage8.jpg');
    thum­b­gen­er­a­tor ('images/030.jpg', 'save', 90, 100, 'thumbs/newimage9.jpg');
    thum­b­gen­er­a­tor ('images/030.jpg', 'save&show', 100, 160, 'thumbs/newimage.jpg');
    ?>

  • Bhupi8

    Hello,

    This is work­ing on IE but not on Mozilla/Netscape.?

  • David

    Thanks so much for the code, this is a life saver… only one prob­lem, all the thumb­nails I cre­ate have a lit­tle black dot in the bot­tom right-hand cor­ner. I've run into this prob­lem on two dif­fer­ent servers, not sure which GD ver­sions either one is run­ning… any ideas?

  • CK

    Yeah, i've the sim­i­lar prob­lem. The thumb­nail cre­ated will have a black line at the bot­tom. But this only hap­pen to some of the pic­tures i've uploaded. Please help.… thanks.

  • Den­nis

    Great code!
    Thank you for sharing

  • shar­if­baba

    hi
    is there any way that i can cre­ate gif ani­mated image from jpeg ,
    image as back­ground and gif image on top of it …

  • michael
  • Ben

    I also suf­fer from the black line blues.… I believe it only occurs with space out­side of the range of the actual desired image dimen­sions when deal­ing with crop­ping, yet I can't seem to fig­ure out how to fix it yet.

  • Pingback: PHP Thumbnail Generator | Danny Kopping | RIA-CODER.COM()

  • karthi

    Hello with lat­est PHP you can also use this

    $ffm­peg = "ffm­peg Installed path"
    $flv­file = "source video file with root path"
    $png_path " "Des­ti­na­tion video file with root path and file type"
    exec("$ffmpeg –y –i $flv­file –vframes 1 –ss 00:01:60 –an –vcodec png –f rawvideo –s 110×90 $png_path");