Compress image and create thumbnail script

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
dalton565
Forum Newbie
Posts: 5
Joined: Wed Jan 30, 2008 8:17 am

Compress image and create thumbnail script

Post by dalton565 »

Hey guys im making a site for my project, and basically it has a facility to upload images of new products. At present it simple uploads the original image and displays it throughout the site. Which is inefficient as where there alot of images loading u may have a few mb loading. Also when i show a thumbnail of the image its still the original size and loads a smaller version of the original image. What im looking to achieve is

1. When the image is uploaded, create a thumbnail of the image reduced in filesize and dimensions
eg i upload an image of 1mb 1024x768 the following happens
- create a thumbnail 100x100px 50kb in size

Is there a simple way to do this in php the only methods ive found via google just reduce the dimensions of the image and not the filesize also.

Ay help thoroughly appreciated

Thanks
R
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: Compress image and create thumbnail script

Post by Christopher »

Look into the GD or ImageMagick extensions. If they are not installed you may be about to exec() them.
(#10850)
bertfour
Forum Commoner
Posts: 45
Joined: Fri Mar 07, 2008 7:33 am

Re: Compress image and create thumbnail script

Post by bertfour »

This is a piece of "thumbnail code" I use...

Hope it makes sense to you....

Code: Select all

 
 
<?php 
 
function createthumb($name,$filename,$new_w,$new_h){
    $src_img=imagecreatefromjpeg($name);
    $old_x=imageSX($src_img);
    $old_y=imageSY($src_img);
    if ($old_x > $old_y) {
        $thumb_w=$new_w;
        $thumb_h=$old_y*($new_h/$old_x);
    }
    if ($old_x < $old_y) {
        $thumb_w=$old_x*($new_w/$old_y);
        $thumb_h=$new_h;
    }
    if ($old_x == $old_y) {
        $thumb_w=$new_w;
        $thumb_h=$new_h;
    }
        $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
        imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 
    imagejpeg($dst_img,$filename); 
    imagedestroy($dst_img); 
    imagedestroy($src_img); 
}
?>
 
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Compress image and create thumbnail script

Post by pickle »

Take a look at http://www.phpgd.com - there's a thumbnailer class there.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply