?
Solved

Resize images

Posted on 2006-05-15
46
Medium Priority
?
567 Views
Last Modified: 2008-02-01
Hello everyone,

I would like some help about resizing images. I am developing an e-commerce site for selling cloths. I have create a control panel in order the administrator of the website to add new products, edit products and general to have control of his stock.
When the administrator adds a new product in the database he uploads also the images for the specific product.[In the site I am using two type of images for the products, the small one and a bigger one which I am using for different pages.] I have manage to write the code for uploading the images to the server using the following code:

PHP Code:
//Check for an product image
if (is_uploaded_file($_FILES['image_small']["tmp_name"]))
    {        
        if (move_uploaded_file($_FILES['image_small']["tmp_name"], "small_images/". $_FILES['image_small']["name"]))
                                {
                                    echo " The image for product has been uploaded! ";
                                   
                                   
                                }else {
                                            echo "The image for product could not be uploaded";
                                            $image='';
                                }
                        $image=$_FILES['image_small']["name"];
                        echo "image". $image;
                        } else {
                                 $image='';
                                 }


the form code
HTML Code:

<form action="" method="post" enctype="multipart/form-data" name="add"> <input name="MAX_FILE_SIZE" type="hidden" value="30000"> <input style="position:absolute; left: 158px; top: 508px;" name="image_small" type="file" >




What I would like help from you is how to resize the images that the administrator uploads to the server.
I would like when the user uploads the image to resize it into two type of dimensions.
The first to be the small image with dimension width:55pixels height:66pixels and the second, width:154, height:198.
I would like also when they are resized to be saved in different folder, for the small in the folder small and for the large images in the folder image.

I tryied to use the imagecopyresampled function but I did not manage to do it.
However, I would really appreciated if you could help me find how to do it.

Thank you very much,
Xenia
Edit/Delete Message
0
Comment
Question by:xenoula
  • 24
  • 17
  • 2
  • +2
46 Comments
 

Author Comment

by:xenoula
ID: 16680893
sorry but i put it in a wrong cateogry , I wanted to put it  in php
0
 
LVL 15

Expert Comment

by:nicholassolutions
ID: 16681666
You may be interested in a short tutorial I wrote on this a while ago:  http://www.nicholassolutions.com/tutorials/php/index.php#cropresize
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 40

Expert Comment

by:Richard Quadling
ID: 16681772
If you have a significant number of images to resize, then external tools like Cerious Software ThumbsPlus may be of use. Nice app which can create all the mono thumbnails for you. Even contact sheets too if your images warrant that sort of thing.
0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 16681774
0
 
LVL 5

Expert Comment

by:dutchclan
ID: 16681951
The logic is usually somthing like this.

1. Upload the image into the "tmp" directive.
2. Create a thump from that directive and either save it to file or database blob.
3. Create a (altered size) image from the original to fit into the site.

step three is to ensure that the image size doesnt "mess up" you template if any. So we parse the image twice. 1 to create a thump and 2 to create the image we like as result for some template.

lets say the max sizes of the thump will be 150x150 and the "larger" version should be somthing like 700x700max.

This is how we do it :D

// Function to calculate the image size //
function calc_dim($old_x, $old_y, $new_x, $new_y){
        if($old_x > $old_y){
            $t_new_x = $new_x;
            $t_new_y = $old_y * ($new_y / $old_x);
        }
        if($old_x < $old_y){
            $t_new_x = $old_x * ($new_x / $old_y);
            $t_new_y = $new_y;
        }
        if($old_x == $old_y){
            $t_new_x = $new_x;
            $t_new_y = $new_y;
        }
        $size = array ('width' => $t_new_x, 'height' => $t_new_y);
        return($size);  
    }

function create_image($source, $new_x, $new_y, $type, $location, $name){
         
        // Create a source pointer
            switch($type){
                case "image/jpeg" :
                    $pointer = ImageCreateFromJpeg($source);
                    $trigger = "1";
                    break;
                case "image/pjpeg" :
                    $pointer = ImageCreateFromJpeg($source);
                    $trigger = "1";
                    break;
                case "image/png" :
                    $pointer = ImageCreateFromPng($source);
                    $trigger = "1";
                    break;
                case "image/xpng" :
                    $pointer = ImageCreateFromPng($source);
                    $trigger = "1";
                    break;
                case "image/gif" :
                    $pointer = imagecreatefromgif($source);
                    $trigger = "2";
                    break;    
            }else{
                echo "type not allowed";
            }
         
        if($trigger = "1"){
            $old_x = imageSX($pointer);
            $old_y = imageSY($pointer);
         
            // Compute size //
            $size = $this->calc_dim($old_x, $old_y, $new_x, $new_y);
             
            if($thump_canvas = ImageCreateTrueColor($size['width'], $size['height'])){
                if(ImageCopyResampled($thump_canvas, $pointer, 0, 0, 0, 0, $size['width'], $size['height'], $old_x, $old_y)){
                    Imagejpeg($thump_canvas, $location.$name.'.jpg', 100);
                    Imagedestroy($thump_canvas);
                    return(true);
                }else{
                    return(false);
                }
            }else{
                return(false);
            }
        }else{    
            $old_x = imageSX($pointer);
            $old_y = imageSY($pointer);
            $size = compute_thump_size($old_x, $old_y, $new_x, $new_y);
         
            if($thump_canvas =imagecreatetruecolor($size['width'], $size['height'])){
                $clr['red']=255;
                  $clr['green']=255;
                  $clr['blue']=255;
                  if($pallet =imagecolorallocate($thump_canvas, $clr['red'],$clr['green'],$clr['blue'])){
                  imagefill($thump_canvas,0,0,$pallet);
                      if(ImageCopyResampled($thump_canvas, $pointer, 0, 0, 0, 0, $size['width'], $size['height'], $old_x, $old_y)){
                            Imagejpeg($thump_canvas, $location.$name.'.jpg', 100);
                            Imagedestroy($thump_canvas);
                            return(true);
                    }else{
                        return(false);
                    }
                  }else{
                      return(false);
                  }
            }else{
                return(false);
            }
        }    
    }

// You are using the upload directives so we dont actually need to "move" the file anymore and worry about rights etc, We just create 2 new ones like this //

if(is_uploaded_file($_FILES['tmp_name']) ){
       $path = './images/uploads/original/';
       $thpath= './images/uploads/thumps/';
      // Thump //
       $width = "150"; $height="150";
      create_image($_FILES['userfile']['tmp_name'], $width, $height, $_FILES[userfile]['type'], basename($_FILES['userfile']['name']), $thpath);
     //Image
         $width = "700"; $height="700";
      create_image($_FILES['userfile']['tmp_name'], $width, $height, $_FILES[userfile]['type'], basename($_FILES['userfile']['name']), $path);
}else{
    //no uploaded file
}

Good Luck!

0
 

Author Comment

by:xenoula
ID: 16683598
Do I have to install the GD graphic library in order to manage do the resizing?
0
 
LVL 15

Expert Comment

by:nicholassolutions
ID: 16683614
yes...although if you use third party software as RQuadling suggested, perhaps not...
0
 

Author Comment

by:xenoula
ID: 16690152
First of all thank you all for your response, however  I feel a little confused.

Can I adjust my code with a code that will resize and put in two diffeent folders the images?
Also how I can install the GD graphic?The php is not installed in my computer, as I connect with FTP with an exernal company that host
php and mysql.

 dutchclan  I used your code but it didn't run

So please more help?

Thank you,
Xenia
 
0
 

Author Comment

by:xenoula
ID: 16691340
The GD library exists so I can use the GD library. However, the code of dutchclan is not working
0
 

Author Comment

by:xenoula
ID: 16692534
I cannot do the resizing, so I would appreciate if somebody could help me adjusting the existing code I have written
to make also resize and store to two different folders.

Thank you in advance,
Xenia
0
 

Author Comment

by:xenoula
ID: 16695509
Please any suggestions?

Thanks
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16695648
form page
<form enctype="multipart/form-data" action="upload.php" method="post">
<input type="file" name="uploadfile"/>
<input type="submit"/>
-------------------------------------------------------

upload.php page
--------------------
<?php
echo  $_POST['txt'];
$uploadedfile = $_FILES['uploadfile']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($uploadedfile);
$newwidth=600;
$newheight=($height/$width)*600;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = "images/". $_FILES['uploadfile']['name'];
imagejpeg($tmp,$filename,100);

imagedestroy($src);
imagedestroy($tmp);
?>


this script requires a folder called images in the same location as the script and has to have write permission on it
this script will work on jpg files. it uses GD lib (ofcourse)

inform me of updates
0
 

Author Comment

by:xenoula
ID: 16697121
Hi dr_debo ,

I tryied your code but is not working ,any suggestions?

Thanks,
Xenia
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16697188
Xenia

try to install php and mysql on your local computer for development, and after that upload your work to the production server. it is not recommended at all that you mess around with a production server!
my code works with me just fine, create a php file with phpinfo(); and in the resulted page search for GD part, after all, gd might not be installed in the first place. also, what is your PHP version ??
0
 

Author Comment

by:xenoula
ID: 16697245
The version of php is PHP Version 4.3.10 and the informaiton for GD are the following:

GD Support       enabled
GD Version       bundled (2.0.28 compatible)
FreeType Support       enabled
FreeType Linkage       with freetype
GIF Read Support       enabled
GIF Create Support       enabled
JPG Support       enabled
PNG Support       enabled
WBMP Support       enabled
XBM Support       enabled

The inital code I wrote that uploads images in the server is working and is strange how the new code cannot work.It says that the image was uploaded but I cannot see teh image.

Thanks
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16697435
not working, like not seeing a result or spitting out errors ??
are u sure that the file upload folder has write permissions ??
0
 

Author Comment

by:xenoula
ID: 16697497
It has the right permissions but still doesn't work.
When I upload the image doesn't give me any errors
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16697620
something is totally screwed here, this code is pretty simple, i tried it on my production server, which uses php.4.3
something is just wrong. maybe your ISP has uploads disabled or something, or you didn't set permission well !!!!

0
 

Author Comment

by:xenoula
ID: 16697659
The strange thing is that when I used my code which is just upload images with the following code it did the upload:

//Check for an product image
if (is_uploaded_file($_FILES['image_small']["tmp_name"]))
      {            
        if (move_uploaded_file($_FILES['image_small']["tmp_name"], "../../images/small_images/". $_FILES['image_small']["name"]))
                                                {
                                                      echo " The image for product has been uploaded! ";
                                                      
                                                      
                                                      
                                                }else {
                                                                  echo "The image for product could not be uploaded";
                                                                  $image='';
                                                }
                                    $image=$_FILES['image_small']["name"];
                                    //echo "image: ". $image;
                                    
                                    
                                    } else {
                                                 $image='';
                                                 }

So I guest if the ISP has uploads displayed or I hadn't gave the correct permisions it shouldn't work neither my code,what you recommend?

Thanks
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16697765
u upload to this folder
"../../images/small_images"
did u adjust that folder in the code i sent u ??

ok, lets try my code with just the upload part, shall we ?
upload.php page
--------------------
<?php
echo (move_uploaded_file($_FILES['uploadfile']['tmp_name'],"images/". $_FILES['uploadfile']['name']))? "upload complete":"Upload failed";
?>
0
 

Author Comment

by:xenoula
ID: 16697821
First of all thank you for your time that you help me, Ok it was uploaded to the server however it was not resized to smaller.

I put in the line of code:
$filename = "../images/small_images/". $_FILES['uploadfile']['name'];

instead of :

$filename = "images/". $_FILES['uploadfile']['name'];

<?php
echo  $_POST['txt'];
$uploadedfile = $_FILES['uploadfile']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($uploadedfile);
$newwidth=600;
$newheight=($height/$width)*600;
$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = "../images/small_images/". $_FILES['uploadfile']['name'];
imagejpeg($tmp,$filename,100);

imagedestroy($src);
imagedestroy($tmp);
?>


Where do you think might be the problem

Thank you
Xenia
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16697973
please note that my code change file size to 600 X ???

upload a jpg file, that is, say 1200X1000 or something
or reduce 600 to a smaller value, say 250 and test the results
0
 

Author Comment

by:xenoula
ID: 16697975
What I notice is that even though I have gave permision to the specific folder and its files
whenever I upload to the specific location it turns the specific image with no privileges
0
 

Author Comment

by:xenoula
ID: 16698079
yes i change the dimension to 50
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16698129
<?php
echo  $_POST['txt'];
$uploadedfile = $_FILES['uploadfile']['tmp_name'];
$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($uploadedfile);

$newwidth=50;  //<------ here

$newheight=($height/$width)*50; //<----- and here

$tmp=imagecreatetruecolor($newwidth,$newheight);
imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);
$filename = "../images/small_images/". $_FILES['uploadfile']['name'];
imagejpeg($tmp,$filename,100);

imagedestroy($src);
imagedestroy($tmp);
?>
0
 

Author Comment

by:xenoula
ID: 16698310
Ok, I just copy and paste what you write but again it doesn't resize it.

I have the following problems:
The first one is that when I succesfully upload an image to the server in the specific folder(which has full privileges)it changes the privilege
to 666 and cannot display the page when I go to the specific url in the browser.

However,when I am going to the server and change again the privileges of the image,it displays the normal size and not the smaller image.
when I go to the absolute url.



0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16698437
try it on my own site
http://www.alatebaa.com/im/

the very very same script, on ur very own PHP version !!!

if it is not folder permission, then it is something magic or from March :)
0
 

Author Comment

by:xenoula
ID: 16698549
Yes you are right I test in your site and is working.

Ok so the directory you are putting in the following code:

$filename = "../images/small_images/". $_FILES['uploadfile']['name'];

is which?

I think also that the problem is with the permissions,however the weard is that I change the privileges but somehow it changes again.
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16698631
i upload to a folder at the same level of my script
images/

try creating  a new folder

just a question, how do u change permissions of the folder ??
0
 

Author Comment

by:xenoula
ID: 16698691
I tryied to change the path in order to store the image general in the website outside from the images folder and is working.
I have an Ftp software called Ipswitch WS_FTP professional and I change from this program.
I had change again with the same program the permission and it was ok.Is there any alterenative way to change them?

I would like to ask you a last question.I want to store in a differnet folder the large images with specific dimensions and in differnet folder
the small images with also specific dimensions.How I can do it regarding your code?

Thank you again,
Xenia
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16698827
just add this line before processing the image

$uploadedfile = $_FILES['uploadfile']['tmp_name'];
copy($_FILES['uploadfile']['tmp_name'],"images/large_". $_FILES['uploadfile']['name']);

here, the uploaded image will be saved as such with a prefix "large_"
0
 

Author Comment

by:xenoula
ID: 16699025
It changes again the right , I can't understand why. I change also the previleges from Dreamweaver also but the same.
What else you think to try in order to change the permissions?

ALso regarding to the follwing code it doesn't resize it now,can you have it a look?

$uploadedfile = $_FILES['uploadfile']['tmp_name'];
copy($_FILES['uploadfile']['tmp_name'],"../large_". $_FILES['uploadfile']['name']);

echo  $_POST['txt'];
$uploadedfile = $_FILES['uploadfile']['tmp_name'];

//copy($_FILES['uploadfile']['tmp_name'],"../large_". $_FILES['uploadfile']['name']);

$src = imagecreatefromjpeg($uploadedfile);
list($width,$height)=getimagesize($uploadedfile);

echo (move_uploaded_file($_FILES['uploadfile']['tmp_name'],"../". $_FILES['uploadfile']['name']))? "upload complete":"Upload failed";

echo "file name ". $_FILES['uploadfile']['name'];

echo "filename ". $filename;


?>

<img src="../<? echo $_FILES['uploadfile']['name']; ?>">

Thanks
0
 
LVL 16

Accepted Solution

by:
dr_dedo earned 2000 total points
ID: 16699117
for the permission, i connect to ftp via IE, and right click a folder -> properties and give write (or full control) to everyone. if u can't manage permisions, contact ur isp

what is that code ?? it is a bite of each post !!

use this
<?php
$uploadedfile = $_FILES['uploadfile']['tmp_name'];
copy($_FILES['uploadfile']['tmp_name'],"images/large_". $_FILES['uploadfile']['name']);
$src = imagecreatefromjpeg($uploadedfile);

list($width,$height)=getimagesize($uploadedfile);

$newwidth=100;
$newheight=($height/$width)*100;
$tmp=imagecreatetruecolor($newwidth,$newheight);

imagecopyresampled($tmp,$src,0,0,0,0,$newwidth,$newheight,$width,$height);

$filename = "images/". $_FILES['uploadfile']['name'];
imagejpeg($tmp,$filename,100);

imagedestroy($src);
imagedestroy($tmp);
?>
<img src="<?=$filename?>">
0
 

Author Comment

by:xenoula
ID: 16699638
Now it is working great apart from the permission, some tims are ok some others are change,anyway I will put them just as it is in the directory.


Thank you very much for your help and your time,

Xenia
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16699726
welcome, glad it finally worked for u
0
 

Author Comment

by:xenoula
ID: 16706770
hi dr_debo,

I have a problem with a problem with the images an dI would like to ask you something?
Some images does not upload them.
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16707117
try the simple code for testing uploads
<?php
echo (move_uploaded_file($_FILES['uploadfile']['tmp_name'],"images/". $_FILES['uploadfile']['name']))? "upload complete":"Upload failed";
?>
0
 

Author Comment

by:xenoula
ID: 16709131
what I want to ask you is till how much has to be the size of the photo in order to resize it?

Because if I have dimention 400*400 or similar it displays only black image
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16710205
if it dislays balck, it means it is not a jpg file. if you have warnning on, you'd see a lot of warnning and division by zero errors and so
0
 

Author Comment

by:xenoula
ID: 16711395
No nothing
0
 

Author Comment

by:xenoula
ID: 16711436
Sorry, it displas that upload was failed.  the image is jpeg but the size is something like 1944x2592.
In the code that you wrote it has restriction about the size of the image?

0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16711470
jpeg is not jpg !
0
 
LVL 16

Expert Comment

by:dr_dedo
ID: 16711476
also check maximum file upload size in php.ini, the default is 2 MB
0
 

Author Comment

by:xenoula
ID: 16711545
jpeg is as jpg ,i check it all in photoshop,all the other images where in jpeg and it upload them.
I didn't find the maximum upload size.

What else you suggest?

Thanks
0
 

Author Comment

by:xenoula
ID: 16711563
100M is the upload_max_filesize
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

These days socially coordinated efforts have turned into a critical requirement for enterprises.
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
Suggested Courses

839 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question