Bikash Mahata Bikash Mahata - 2 years ago 77
PHP Question

How to re-size image and upload in different folder with different size?

I am new in php. For my shopping website project I need your help.

In my add_product page I have product image option. When I submit the form the File image will re-size in 3 different size in different folder like-

30x30 for Shopping cart icon in 'Product/Image/Icon' folder.
170x300 for Base image in 'Product/Image/Base' folder.
400x300 for Large View in 'Product/Image/Thumb' folder.

I have also a database table -

Product ID

After submit form also each file generate a unique new name and saved in the above table in like -

ID : Auto increment
Product ID : 44545
thumb_name : new file name here
thumb_type: Base Image

How to re-size image and upload in different folder with different size and insert the file name in MySQL database? Plz help me any one.

Answer Source
  1. After upload store only image base name to the database eg. product1.jpg
  2. then create thumbs with same name in different directories..

    uploaded file - uploads/product1.jpg
    small thumb - uploads/thumbs/small/product1.jpg

here is a function to create thumb in php

function createThumb($filepath, $thumbPath, $maxwidth, $maxheight, $quality=75)
            $file_name  = pathinfo($filepath);  
            $format = $file_name['extension'];
            // Get new dimensions
            $newW   = $maxwidth;
            $newH   = $maxheight;

            // Resample
            $thumb = imagecreatetruecolor($newW, $newH);
            $image = imagecreatefromstring(file_get_contents($filepath));
            list($width_orig, $height_orig) = getimagesize($filepath);
            imagecopyresampled($thumb, $image, 0, 0, 0, 0, $newW, $newH, $width_orig, $height_orig);

            // Output
            switch (strtolower($format)) {
                case 'png':
                imagepng($thumb, $thumbPath, 9);

                case 'gif':
                imagegif($thumb, $thumbPath);

                imagejpeg($thumb, $thumbPath, $quality);
            return $created;    

parameter details

$filepath // uploaded file path include name eg. uploads/product1.jpg
$thumbPath // thumbpath with name eg. uploads/thumbs/small/product1.jpg
$maxwidth // width for the thumb eg. 100
$maxheight// height for the thumb eg. 60
$quality=75 // quality for the thumb image 1 - 100 default it is 75
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download