Solved

GD Image Resizing

Posted on 2006-10-24
22
363 Views
Last Modified: 2008-02-07

im looking to resize images that are uploaded to a basic standard.

Example:

User A Uploads an image that is 2MB, and the proposed function resizes the image to 160 Width, leaving the Height (keeping the aspect ratio), then Converting it to a LOW Quality (10-20%) JPG, then the SQL upload code continues to insert it into the DB.

So Resize
Resample
Present for DB Query

Anyone got a class that easily handles this or something?

I'm running PHP 4.4.4 & mySQL btw


-n
0
Comment
Question by:n8dog
  • 11
  • 11
22 Comments
 

Author Comment

by:n8dog
ID: 17800567
Here is the code I have now that allows me to upload...

Im looking to integrate a RESIZER into this.

The Height is to be hard coded to 160px.

Code
-----------------------------

//picture upload portion #######################################

if( ($upload) && ($_FILES['userfile']['size']!=0) ){
  if( ($upload) && ($_FILES['userfile']['size']<50000) ){
      $fileName = $_FILES['userfile']['name'];
      $tmpName  = $_FILES['userfile']['tmp_name'];
      $fileSize = $_FILES['userfile']['size'];
      $fileType = $_FILES['userfile']['type'];

      $fp = fopen($tmpName, 'r');
      $content = fread($fp, filesize($tmpName));
      $content = addslashes($content);
      fclose($fp);
 if(!get_magic_quotes_gpc()){
    $fileName = addslashes($fileName);
            }

$query = "UPDATE datingpics SET name='$fileName', size='$fileSize', type='$fileType', content='$content' WHERE userid='$uid'";

mysql_query($query) or die('Error, Update Failed!');

0
 
LVL 4

Expert Comment

by:anilande
ID: 17810377
<?php
// File and new size
$filename = 'test.jpg';
$percent = 0.5;

// Content type
header('Content-type: image/jpeg');

// Get new sizes
list($width, $height) = getimagesize($filename);
$newwidth = $width * $percent;
$newheight = $height * $percent;

// Load
$thumb = imagecreatetruecolor($newwidth, $newheight);
$source = imagecreatefromjpeg($filename);

// Resize
imagecopyresized($thumb, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);

// Output
//imagejpeg($thumb);

$fp = fopen($thumb, 'r');
$content = fread($fp, filesize($thumb));
$content = addslashes($content);
fclose($fp);

$query = "UPDATE datingpics SET name='$fileName', size='$fileSize', type='$fileType', content='$content' WHERE userid='$uid'";
?>


other details u will find at

http://in2.php.net/manual/en/function.imagecopyresized.php
0
 

Author Comment

by:n8dog
ID: 17813857
So this will permanently resize the image uploaded?

if so, awesome!

I will try this code out. - thanks!

n8Dog
0
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 

Author Comment

by:n8dog
ID: 17839778
is this resizing, or just viewing it resized?
0
 

Author Comment

by:n8dog
ID: 17839818
i tried this code, it doesnt work.

looks like a direct copy & paste from the link you posted.

-n
0
 
LVL 4

Expert Comment

by:anilande
ID: 17840094
hi

for me the script works fine. please check if php has GD liberary enabled. use phpinfo().
to get this script running php must support GD liberary.

it is resizing the image. u can check that by checking the the size of the thumb file.
the thumb image will be distorted since GD doesn't do a perfect resize.
so i will suggest use imagemagik for resizing image.

regards
anilande
0
 

Author Comment

by:n8dog
ID: 17840109
yes, it is enabled.

what is image magik?

0
 
LVL 4

Expert Comment

by:anilande
ID: 17840117
it an opensource application most of the webhosting providers provide service of imagemagic because it does a perfect resize of an image.

can u tell me what error it is throwing??

anilande
0
 

Author Comment

by:n8dog
ID: 17840118
Here is the complete code I am using. I tried to integrate what you had, but i might have not gotten it right.

can you integrate your resize solution with this?

code
---------------------------------------------

// variables
      
      
      $upload                                                = $_POST['profilepics_image_upload'];
      $profilepics_ownerid      = $_SESSION['userid'];
      

      //picture upload portion #######################################
            ?> <center> <?
            
      if( ($upload) && ($_FILES['profilepics_image']['size']!=0) ){
      
            
            if( ($upload) && ($_FILES['profilepics_image']['size']<50000) ){

                        $profilepics_image_name = $_FILES['profilepics_image']['name'];
                        $tmpName                                            = $_FILES['profilepics_image']['tmp_name'];
                        $profilepics_image_size = $_FILES['profilepics_image']['size'];
                        $profilepics_image_type = $_FILES['profilepics_image']['type'];

                        $fp = fopen($tmpName, 'r');

                        $profilepics_image       = fread($fp, filesize($tmpName));
                        $profilepics_image       = addslashes($profilepics_image);
                        fclose($fp);

            if(!get_magic_quotes_gpc()){
          $profilepics_image_name = addslashes($profilepics_image_name);
            }
            
                  //      check for existing image
                  $sql_imagechk             = mysql_query("SELECT imagename, imagetype, imagesize, image FROM profilepics WHERE ownerid = '$profilepics_ownerid'") or die (mysql_error());
                  $numimages                        =      mysql_numrows($sql_imagechk);
            
            
            if( $numimages==0 ){
                  //      insert picture
                  $sql_imageinsert       = mysql_query("INSERT INTO profilepics (ownerid, image, imagetype, imagesize, imagename) VALUES('$profilepics_ownerid', '$profilepics_image', '$profilepics_image_type', '$profilepics_image_size', '$profilepics_image_name') ") or die (mysql_error());
            }elseif( $numimages==1){
                  //      update picture
                  $sql_imageupdate      = mysql_query("UPDATE profilepics SET image='$profilepics_image', imagetype='$profilepics_image_type', imagesize='$profilepics_image_size', imagename='$profilepics_image_name' WHERE ownerid='$profilepics_ownerid'") or die (mysql_error());
            }
      
                  //$query = "UPDATE profilepics SET imagename='$profile_image_name', imagesize='$profile_image_size', imagetype='$profile_image_type', image='$profile_image' WHERE ownerid='$uid'";
                  //mysql_query($query) or die('Error, Update Failed!');
      
                  echo "<br><h2>Picture $profilepics_image_name Saved/Updated Successfully</h2><br> <input type=button value=Continue onclick=history.back()  class=btn> ";
            
            }elseif( ($upload) && ($_FILES['profilepics_image']['size']>50000) ){

                  $profile_image_name = $_FILES['profilepics_image']['name'];
                  $profile_image_size = $_FILES['profilepics_image']['size'];
                  
                  ?>
                  <hr width=450 color=black>
                  <h2>
                  The file size of the image you tried to Save was TOO LARGE</h2> <br>
                  <h3>
                        File Name: <font color=black><? echo $profilepics_image_name; ?></font> File Size: <? echo substr($profilepics_image_size,0,3).'KB'; ?><br><br>
                        The picture must be under 50KB - Your picture was: <? echo substr($profilepics_image_size,0,3).'KB'; ?><br><br>
                        Please Reduce and Try Again
                        <br><br>
                        <input type="button" value="Continue" onclick="history.back()" class="btn">
                  </h3>
                        
                        <?
            }

}
                  
            ?> </center> <?
      
            //end picture upload #######################################
0
 
LVL 4

Expert Comment

by:anilande
ID: 17840123
u can find details about imagemagick at

http://www.imagemagick.org/script/index.php.
0
 
LVL 4

Expert Comment

by:anilande
ID: 17840127
where are u resizing the image?
0
 

Author Comment

by:n8dog
ID: 17840139
i posted the version that IS NOT incorporating the code you provided.

when i incorporated your solution, the content uploaded into the BLOB in my DB was blank...

:(

0
 
LVL 4

Accepted Solution

by:
anilande earned 500 total points
ID: 17840165
i hope this is what u need i ahve added the function resize on the top and the code with my name th comment. check and tell me the status


<?php

function Resize($Image,$NewImage,$MaxWidth,$MaxHeight,$Quality) {
  list($ImageWidth,$ImageHeight,$TypeCode)=getimagesize($Image);
  $ImageType=($TypeCode==1?"gif":($TypeCode==2?"jpeg":
             ($TypeCode==3?"png":FALSE)));
  $CreateFunction="imagecreatefrom".$ImageType;
  $OutputFunction="image".$ImageType;
  if ($ImageType) {
   $Ratio=($ImageHeight/$ImageWidth);
   $ImageSource=$CreateFunction($Dir.$Image);
   if ($ImageWidth > $MaxWidth || $ImageHeight > $MaxHeight) {
     if ($ImageWidth > $MaxWidth) {
         $ResizedWidth=$MaxWidth;
         $ResizedHeight=$ResizedWidth*$Ratio;
     }
     else {
       $ResizedWidth=$ImageWidth;
       $ResizedHeight=$ImageHeight;
     }      
     if ($ResizedHeight > $MaxHeight) {
       $ResizedHeight=$MaxHeight;
       $ResizedWidth=$ResizedHeight/$Ratio;
     }    
     $ResizedImage=imagecreatetruecolor($ResizedWidth,$ResizedHeight);
     imagecopyresampled($ResizedImage,$ImageSource,0,0,0,0,$ResizedWidth,
                         $ResizedHeight,$ImageWidth,$ImageHeight);
   }
   else {
     $ResizedWidth=$ImageWidth;
     $ResizedHeight=$ImageHeight;    
     $ResizedImage=$ImageSource;
   }  
   $OutputFunction($ResizedImage,$NewImage,$Quality);
   return true;
  }  
  else
   return false;
}


     
     $upload= $_POST['profilepics_image_upload'];
     $profilepics_ownerid= $_SESSION['userid'];
     

     //picture upload portion #######################################
          ?> <center> <?
         
     if( ($upload) && ($_FILES['profilepics_image']['size']!=0) ){
     
         
          if( ($upload) && ($_FILES['profilepics_image']['size']<50000) ){

                    $profilepics_image_name = $_FILES['profilepics_image']['name'];
                    $tmpName                                     = $_FILES['profilepics_image']['tmp_name'];
                    $profilepics_image_size = $_FILES['profilepics_image']['size'];
                    $profilepics_image_type = $_FILES['profilepics_image']['type'];
                              ///////////////////////anilande//////////////////////////////////
                              list($width, $height) = getimagesize($tmpName);
                              $percent = 0.5;
                              $newwidth = $width * $percent;
                              $newheight = $height * $percent;
                              Resize('',$tmpName,'',$tmpName,$newwidth,$newheight,100);
                              /////////////////////////////////////////////////////////////////
                    $fp = fopen($tmpName, 'r');

                    $profilepics_image      = fread($fp, filesize($tmpName));
                    $profilepics_image      = addslashes($profilepics_image);
                    fclose($fp);

          if(!get_magic_quotes_gpc()){
         $profilepics_image_name = addslashes($profilepics_image_name);
          }
         
               //     check for existing image
               $sql_imagechk           = mysql_query("SELECT imagename, imagetype, imagesize, image FROM profilepics WHERE ownerid = '$profilepics_ownerid'") or die (mysql_error());
               $numimages                    =     mysql_numrows($sql_imagechk);
         
         
          if( $numimages==0 ){
               //     insert picture
               $sql_imageinsert      = mysql_query("INSERT INTO profilepics (ownerid, image, imagetype, imagesize, imagename) VALUES('$profilepics_ownerid', '$profilepics_image', '$profilepics_image_type', '$profilepics_image_size', '$profilepics_image_name') ") or die (mysql_error());
          }elseif( $numimages==1){
               //     update picture
               $sql_imageupdate     = mysql_query("UPDATE profilepics SET image='$profilepics_image', imagetype='$profilepics_image_type', imagesize='$profilepics_image_size', imagename='$profilepics_image_name' WHERE ownerid='$profilepics_ownerid'") or die (mysql_error());
          }
     
               //$query = "UPDATE profilepics SET imagename='$profile_image_name', imagesize='$profile_image_size', imagetype='$profile_image_type', image='$profile_image' WHERE ownerid='$uid'";
               //mysql_query($query) or die('Error, Update Failed!');
     
               echo "<br><h2>Picture $profilepics_image_name Saved/Updated Successfully</h2><br> <input type=button value=Continue onclick=history.back()  class=btn> ";
         
          }elseif( ($upload) && ($_FILES['profilepics_image']['size']>50000) ){

               $profile_image_name = $_FILES['profilepics_image']['name'];
               $profile_image_size = $_FILES['profilepics_image']['size'];
               
               ?>
               <hr width=450 color=black>
               <h2>
               The file size of the image you tried to Save was TOO LARGE</h2> <br>
               <h3>
                    File Name: <font color=black><? echo $profilepics_image_name; ?></font> File Size: <? echo substr($profilepics_image_size,0,3).'KB'; ?><br><br>
                    The picture must be under 50KB - Your picture was: <? echo substr($profilepics_image_size,0,3).'KB'; ?><br><br>
                    Please Reduce and Try Again
                    <br><br>
                    <input type="button" value="Continue" onclick="history.back()" class="btn">
               </h3>
                   
                    <?
          }

}
               
          ?> </center>


0
 
LVL 4

Expert Comment

by:anilande
ID: 17840168
sorry chenage the resize function in the commented section with this one

Resize($tmpName,$tmpName,$newwidth,$newheight,100);
0
 

Author Comment

by:n8dog
ID: 17840198
instead of the percentage setting, is it possible to absolute size it. For example: Absolute: Width=140, Height=variable ?

basically what i have is a situation where users upload images, but i need them to always be resized to a standard.

the exact standard is 140 x 160 (w x h), however anything 140 x Z is fine

understand?
0
 
LVL 4

Expert Comment

by:anilande
ID: 17840515
update following variables

ex..
$newwidth = 500;
$newheight = 600;
0
 

Author Comment

by:n8dog
ID: 17840653
GREAT!

it works!

I have a question though.. i would like to maintain the Aspect Ratio... anf just resize the Width to 140, and let the Height adjust automatically to the size ratio relative to 140.

Know how?

-n8
0
 
LVL 4

Expert Comment

by:anilande
ID: 17840681
thats what we are doing here we are mentioning that the image should be resixed to

if $newwidth>500
image size must =  500 X z
and if newheight >600
image size must =  z X 600

where z=relative other dimention

we are keeping the aspect ration.

anilande

0
 
LVL 4

Expert Comment

by:anilande
ID: 17840691
sorry i didn't check the dimentions

just change the $newwidth=140 in place of 500


and for your condition

put function statement as
$newwidth = 140;
$newheight =1000;

Resize($tmpName,$tmpName,$newwidth,$newheight,100);

anilande
0
 

Author Comment

by:n8dog
ID: 17840714
So use this?

list($width, $height) = getimagesize($tmpName);
        //   REMOVED $percent = 0.5;
        $newwidth       = 200;
        $newheight       = 1000;
                        
         Resize($tmpName,$tmpName,$newwidth,$newheight,80);


-n
0
 

Author Comment

by:n8dog
ID: 17840722
im trying this code block out, and it's really working GREAT!

i really appreciate your diligence in the matter.

:)

-n8
0
 
LVL 4

Expert Comment

by:anilande
ID: 17840730
thanks :)
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

I imagine that there are some, like me, who require a way of getting currency exchange rates for implementation in web project from time to time, so I thought I would share a solution that I have developed for this purpose. It turns out that Yaho…
Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…

776 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