Creating image thumbnails with PHP!

Discussion in 'PHP' started by pradeep, Sep 3, 2005.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    If we intend to make an image gallery, and we would like to show the thumbails of the images, it wouldn't be a wise idea to show the original images with their height & width modified in the <img> tag, that would result in low image quality & higher download time. The solution to this problem would be creating thumbnails at the server end and display them instead.
    This solution can be approached in two ways, you can create the thumbnails once and for all or create thumbnails everytime at runtime.
    For this purpose, I wrote a class which will create the thumbnail.

    The class:
    PHP:
    /* 
     *    File        :    thumb.class.php
     *    Description    :    Class for creating thumbnails
     */
     
     
    class Thumb
     
    {
         var 
    $filename;
         var 
    $img;
         var 
    $height;
         var 
    $width;
         var 
    $ratio 10;
         var 
    $oldim;
         var 
    $oldh;
         var 
    $oldw;
     
     
         function 
    filename($file/* used for setting filename */
         
    {
             
    $this->filename $file;
         }
     
         function 
    setRatio($ratio/* used for setting ratio */
         
    {
             
    $this->ratio $ratio;
         }
     
         function 
    init() /* creates the GD stream */
         
    {
             
    $this->img imagecreatetruecolor($this->width,$this->height);
         }
     
         function 
    calculateSize() /* to calculate the output size */
         
    {
             
    //$this->info = getimagesize($this->filename); /* returns height,width,type,attribute */
             
    $this->oldim imagecreatefromjpeg($this->filename);
             
    $this->oldw imagesx($this->oldim);
             
    $this->oldh imagesy($this->oldim);
     
             
    /* code to re-calculate size maintaining the aspect ratio */
             
    $this->width = ($this->oldw/100)*$this->ratio;
             
    $this->height = ($this->oldh/100)*$this->ratio;
     
             
    $this->init();
             return 
    true;
         }
     
         function 
    finish()
         {
             
    $this->calculateSize();
     
    imagecopyresampled($this->img,$this->oldim,0,0,0,0,$this->width,$this->height,$this->oldw,$this->oldh);
             
    header("Content-Type: image/jpeg");
             
    imagejpeg($this->img);
         }
     }
    An example:
    PHP:
    <?
     require_once(
    "thumb.class.php");
     
     
    $im = new Thumb;
     
    $im->filename("abhishek.jpg");
     
    $im->setRatio(10);
     
    $im->finish();
     
     
    ?>
     
    Hope, everyone likes this, you have any suggestions please let me know.
     
  2. rekha

    rekha New Member

    Joined:
    Jan 17, 2008
    Messages:
    83
    Likes Received:
    0
    Trophy Points:
    0
    Hi,

    Your articles are really nice.

    I want to create thumbnails from a swf file.How can I do it.I tried FFMPEG but it is not working for swf files.


    Any help will be appreciated.
     
  3. jaksonx

    jaksonx New Member

    Joined:
    Sep 22, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Re: online PHP scripts!

    Hi, you have shared really useful information with us. It has lots of worth for those people who want to start web hosting business. I'm running my own online business successfully with help of it provides me scripts to make easier to my business. I'm very thankful to that caters such kind of great services. Guru script is also a great resource for those guys who are wondering to start their online business. I hope my info will help to many beginners in online world.

    Thanks!
     
  4. Max2010

    Max2010 New Member

    Joined:
    Oct 14, 2010
    Messages:
    17
    Likes Received:
    1
    Trophy Points:
    0
    Home Page:
    http://www.logoarena.com
    I used GD libraries too, now I'm using image magick with Imagick php libraries.
    It's easy as:
    ...
    $im = new Imagick($image_filename);
    $im->resizeImage($x, $y, imagick::FILTER_LANCZOS, 1);
    $im->writeImage($thumbnail_filename);
    ...

    And it's better quality. Problem is that not any server has image magick installed.
    Thanks for sharing!
     
  5. shrikrishnatech

    shrikrishnatech New Member

    Joined:
    Nov 19, 2010
    Messages:
    42
    Likes Received:
    4
    Trophy Points:
    0
    Occupation:
    Wordpress theme, Wordpress Theming, WP Themes, Cor
    Home Page:
    http://www.shrikrishnatechnologies.com
    This code is also useful

    Code:
    [FONT=Verdana, Arial, Helvetica, sans-serif][SIZE=2][FONT=Verdana, Arial, Helvetica, sans-serif][SIZE=2][FONT=Verdana, Arial, Helvetica, sans-serif][SIZE=2][FONT=Verdana, Arial, Helvetica, sans-serif][SIZE=2][FONT=Verdana, Arial, Helvetica, sans-serif][SIZE=2][FONT=Verdana, Arial, Helvetica, sans-serif][SIZE=2][FONT=Verdana, Arial, Helvetica, sans-serif][SIZE=2][FONT=Courier][COLOR=#555555]?php
    [COLOR=#428ac9]//define a maxim size for the uploaded images[/COLOR]
    define ("MAX_SIZE","100"); 
    [COLOR=#428ac9]// define the width and height for the thumbnail[/COLOR]
    [COLOR=#428ac9]// note that theese dimmensions are considered the maximum dimmension and are not fixed, [/COLOR]
    [COLOR=#428ac9]// because we have to keep the image ratio intact or it will be deformed[/COLOR]
    define ("WIDTH","150"); 
    define ("HEIGHT","100"); 
    
     [COLOR=#428ac9]// this is the function that will create the thumbnail image from the uploaded image[/COLOR]
    [COLOR=#428ac9]// the resize will be done considering the width and height defined, but without deforming the image[/COLOR]
    function make_thumb($img_name,$filename,$new_w,$new_h)
    {
    [COLOR=#428ac9]    //get image extension.[/COLOR]
        $ext=getExtension($img_name);
    [COLOR=#428ac9]    //creates the new image using the appropriate function from gd library[/COLOR]
        if(!strcmp("jpg",$ext) || !strcmp("jpeg",$ext))
            $src_img=imagecreatefromjpeg($img_name);
    
         if(!strcmp("png",$ext))
            $src_img=imagecreatefrompng($img_name);
    
         [COLOR=#428ac9]    //gets the dimmensions of the image[/COLOR]
        $old_x=imageSX($src_img);
        $old_y=imageSY($src_img);
    
         [COLOR=#428ac9]    // next we will calculate the new dimmensions for the thumbnail image[/COLOR]
    [COLOR=#428ac9]    // the next steps will be taken: [/COLOR]
    [COLOR=#428ac9]    //     1. calculate the ratio by dividing the old dimmensions with the new ones[/COLOR]
    [COLOR=#428ac9]    //        2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable[/COLOR]
    [COLOR=#428ac9]    //            and the height will be calculated so the image ratio will not change[/COLOR]
    [COLOR=#428ac9]    //        3. otherwise we will use the height ratio for the image[/COLOR]
    [COLOR=#428ac9]    // as a result, only one of the dimmensions will be from the fixed ones[/COLOR]
        $ratio1=$old_x/$new_w;
        $ratio2=$old_y/$new_h;
        if($ratio1>$ratio2)    {
            $thumb_w=$new_w;
            $thumb_h=$old_y/$ratio1;
        }
        else    {
            $thumb_h=$new_h;
            $thumb_w=$old_x/$ratio2;
        }
    
     [COLOR=#428ac9]    // we create a new image with the new dimmensions[/COLOR]
        $dst_img=ImageCreateTrueColor($thumb_w,$thumb_h);
    
         [COLOR=#428ac9]    // resize the big image to the new created one[/COLOR]
        imagecopyresampled($dst_img,$src_img,0,0,0,0,$thumb_w,$thumb_h,$old_x,$old_y); 
    
         [COLOR=#428ac9]    // output the created image to the file. Now we will have the thumbnail into the file named by $filename[/COLOR]
        if(!strcmp("png",$ext))
            imagepng($dst_img,$filename); 
        else
            imagejpeg($dst_img,$filename); 
    
     [COLOR=#428ac9]    //destroys source and destination images. [/COLOR]
        imagedestroy($dst_img); 
        imagedestroy($src_img); 
    }
    
    [COLOR=#428ac9]// This function reads the extension of the file. [/COLOR]
    [COLOR=#428ac9]// It is used to determine if the file is an image by checking the extension. [/COLOR]
    function getExtension($str) {
            $i = strrpos($str,".");
            if (!$i) { return ""; }
            $l = strlen($str) - $i;
            $ext = substr($str,$i+1,$l);
            return $ext;
    }
    
    [COLOR=#428ac9]// This variable is used as a flag. The value is initialized with 0 (meaning no error found) 
    and it will be changed to 1 if an errro occures. If the error occures the file will not be uploaded.[/COLOR]
    $errors=0;
    [COLOR=#428ac9]// checks if the form has been submitted[/COLOR]
    if(isset($_POST['Submit']))
    {
    [COLOR=#428ac9]//reads the name of the file the user submitted for uploading[/COLOR]
        $image=$_FILES['image']['name'];
    [COLOR=#428ac9]    // if it is not empty[/COLOR]
        if ($image) 
        {
    [COLOR=#428ac9]        // get the original name of the file from the clients machine[/COLOR]
            $filename = stripslashes($_FILES['image']['name']);
            
    [COLOR=#428ac9]        // get the extension of the file in a lower case format[/COLOR]
             $extension = getExtension($filename);
            $extension = strtolower($extension);
    [COLOR=#428ac9]        // if it is not a known extension, we will suppose it is an error, print an error message 
            and will not upload the file, otherwise we continue[/COLOR]
            if (($extension != "jpg")  && ($extension != "jpeg") && ($extension != "png"))    
            {
                echo '<h1>Unknown extension!</h1>';
                $errors=1;
            }
            else
            {
    [COLOR=#428ac9]            // get the size of the image in bytes[/COLOR]
    [COLOR=#428ac9]            // $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which the uploaded file was stored on the server[/COLOR]
                $size=getimagesize($_FILES['image']['tmp_name']);
                $sizekb=filesize($_FILES['image']['tmp_name']);
    
                 [COLOR=#428ac9]            //compare the size with the maxim size we defined and print error if bigger[/COLOR]
                if ($sizekb > MAX_SIZE*1024)
                {
                    echo '<h1>You have exceeded the size limit!</h1>';
                    $errors=1;
                }
    
     [COLOR=#428ac9]            //we will give an unique name, for example the time in unix time format[/COLOR]
                $image_name=time().'.'.$extension;
    [COLOR=#428ac9]            //the new name will be containing the full path where will be stored (images folder)[/COLOR]
                 $newname="images/".$image_name;
                $copied = copy($_FILES['image']['tmp_name'], $newname);
    [COLOR=#428ac9]            //we verify if the image has been uploaded, and print error instead[/COLOR]
                if (!$copied) 
                {
                    echo '<h1>Copy unsuccessfull!</h1>';
                    $errors=1;
                }
                else
                {
    [COLOR=#428ac9]                // the new thumbnail image will be placed in images/thumbs/ folder[/COLOR]
                    $thumb_name='images/thumbs/thumb_'.$image_name;
    [COLOR=#428ac9]                // call the function that will create the thumbnail. The function will get as parameters 
                    the image name, the thumbnail name and the width and height desired for the thumbnail[/COLOR]
                    $thumb=make_thumb($newname,$thumb_name,WIDTH,HEIGHT);
                }}    }}
    
     [COLOR=#428ac9]//If no errors registred, print the success message and show the thumbnail image created[/COLOR]
    if(isset($_POST['Submit']) && !$errors) 
    {
        echo "<h1>Thumbnail created Successfully!</h1>";
        echo '<img src="'.$thumb_name.'">';
    }
    
     ?>
    [COLOR=#428ac9]<!-- next comes the form, you must set the enctype to "multipart/form-data" and use an input type "file"  -->[/COLOR]
    
     <form name="newad" method="post" enctype="multipart/form-data"  action="">
    <table>
        <tr><td><input type="file" name="image" ></td></tr>
        <tr><td><input name="Submit" type="submit" value="Upload image"></td></tr>
    </table>    
    </form>[/COLOR][/FONT][/SIZE][/FONT][/SIZE][/FONT][/SIZE][/FONT][/SIZE][/FONT][/SIZE][/FONT][/SIZE][/FONT][/SIZE][/FONT]
     
  6. parryndsxl

    parryndsxl New Member

    Joined:
    Nov 19, 2010
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://www.ndsxl.com
    hi..

    How to make the shopping cart site with free website creator..??? meet again.
     
  7. shamilahamed

    shamilahamed New Member

    Joined:
    Mar 9, 2010
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    hii tat was an very useful yaar!
     
  8. shamilahamed

    shamilahamed New Member

    Joined:
    Mar 9, 2010
    Messages:
    5
    Likes Received:
    0
    Trophy Points:
    0
    can any one help me..
    how to write an php code for checkboxs..
    code for checking all and unchecking the checkbox..
     
  9. kajal123

    kajal123 New Member

    Joined:
    Mar 7, 2011
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Hi friends,,,,I think this article is very nice., you have shared really useful information with us. It has lots of worth for those people who want to start web hosting business. I'm running my own online business successfully with help of it provides me scripts to make easier to my business. I'm very thankful to that caters such kind of great services..........thanks for sharing that.........regards,,,,
    kajal,,:):):)
     
  10. marksteven

    marksteven New Member

    Joined:
    Mar 13, 2011
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Occupation:
    Business
    Location:
    Manhatten, New York, USA
    Home Page:
    http://www.listentoearn.com
    This are really good coding of PHP! Thank you
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice