Jump to content

PHP thumbnail resizing/cropping.


Transmission94

Recommended Posts

Hi there!

 

I have asked questions here before and you guys are so good at helping out that I figured there was no better place to try an get help! :)

 

Here's my issue:

 

I am fairly new to PHP, and I am writing a script that will resize images.

 

First an uploaded image is resized to 800width by *height, depending on the orientation of the file uploaded (portrait/landscape).

 

The script is then meant to create a thumbnail of that image. The thumbnail must be 175width by 117height. This is has the same proportion as a standard jpeg image from the cameras that take the pictures, thus there is no need to crop the image for a thumbnail version if the original file is landscape. However, when the uploaded image is portrait orientation I must crop image to be able to achieve a thumbnail of 175x117px. When cropping, I need to maintain the center of the image (as opposed to the top left, bottom right, etc.)

 

I am having massive trouble doing this, and I would really be eternally grateful if someone would mind taking the time to look through my code and help me out! :D

 

The site can be found at hybridtempo.net. Beware that there is some pretty random shit in the database, where I had to enter random data and ran out of ideas, lol.

 

Everything seems to work fine until very near the bottom, where I begin to use the 'imagecopyresize', 'imagecreatetruecolour', 'imagecreatefromjpeg', etc. functions.

 

Thanks very much for any contribution. :)

 

Without further ado:

 

<?php


//IMAGE RESIZE FUNCTION CODE BEGIN - CODE FOUND AND APPROPRIATED FROM http://github.com/maxim/smart_resize_image/

function smart_resize_image($file,
                              $width              = 0, 
                              $height             = 0, 
                              $proportional       = false, 
                              $output             = 'file', 
                              $delete_original    = true, 
                              $use_linux_commands = false ) {

    if ( $height <= 0 && $width <= 0 ) return false;

    # Setting defaults and meta
    $info                         = getimagesize($file);
    $image                        = '';
    $final_width                  = 0;
    $final_height                 = 0;
    list($width_old, $height_old) = $info;

    # Calculating proportionality
    if ($proportional) {
      if      ($width  == 0)  $factor = $height/$height_old;
      elseif  ($height == 0)  $factor = $width/$width_old;
      else                    $factor = min( $width / $width_old, $height / $height_old );

      $final_width  = round( $width_old * $factor );
      $final_height = round( $height_old * $factor );
    }
    else {
      $final_width = ( $width <= 0 ) ? $width_old : $width;
      $final_height = ( $height <= 0 ) ? $height_old : $height;
    }

    # Loading image to memory according to type
    switch ( $info[2] ) {
      case IMAGETYPE_GIF:   $image = imagecreatefromgif($file);   break;
      case IMAGETYPE_JPEG:  $image = imagecreatefromjpeg($file);  break;
      case IMAGETYPE_PNG:   $image = imagecreatefrompng($file);   break;
      default: return false;
    }


    # This is the resizing/resampling/transparency-preserving magic
    $image_resized = imagecreatetruecolor( $final_width, $final_height );
    if ( ($info[2] == IMAGETYPE_GIF) || ($info[2] == IMAGETYPE_PNG) ) {
      $transparency = imagecolortransparent($image);

      if ($transparency >= 0) {
        $transparent_color  = imagecolorsforindex($image, $trnprt_indx);
        $transparency       = imagecolorallocate($image_resized, $trnprt_color['red'], $trnprt_color['green'], $trnprt_color['blue']);
        imagefill($image_resized, 0, 0, $transparency);
        imagecolortransparent($image_resized, $transparency);
      }
      elseif ($info[2] == IMAGETYPE_PNG) {
        imagealphablending($image_resized, false);
        $color = imagecolorallocatealpha($image_resized, 0, 0, 0, 127);
        imagefill($image_resized, 0, 0, $color);
        imagesavealpha($image_resized, true);
      }
    }
    imagecopyresampled($image_resized, $image, 0, 0, 0, 0, $final_width, $final_height, $width_old, $height_old);

    # Taking care of original, if needed
    if ( $delete_original ) {
      if ( $use_linux_commands ) exec('rm '.$file);
      else @unlink($file);
    }

    # Preparing a method of providing result
    switch ( strtolower($output) ) {
      case 'browser':
        $mime = image_type_to_mime_type($info[2]);
        header("Content-type: $mime");
        $output = NULL;
      break;
      case 'file':
        $output = $file;
      break;
      case 'return':
        return $image_resized;
      break;
      default:
      break;
    }

    # Writing image according to type to the output destination
    switch ( $info[2] ) {
      case IMAGETYPE_GIF:   imagegif($image_resized, $output);    break;
      case IMAGETYPE_JPEG:  imagejpeg($image_resized, $output);   break;
      case IMAGETYPE_PNG:   imagepng($image_resized, $output);    break;
      default: return false;
    }

    return true;
  }


//IMAGE RESIZE FUNCTION CODE END.



/******** IMAGE UPLOAD SCRIPT BEGIN ********/

//IF IMAGE IS JPEG OR PNG
if (($_FILES["file"]["type"] == "image/png")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/pjpeg"))
{
    //IF THERE IS AN ERROR, DISPLAY THE MESSAGE
    if ($_FILES["file"]["error"] > 0)
    {
        echo "<p>Error: " . $_FILES["file"]["error"] . "
        <br />
        Redirecting...
        <br />
        <br />
        If you are not automatically redirected after 3 seconds, <b><a href='addproduct_uploadimage.php'>click here to try another upload.</a></p>";

        //REDIRECT
        echo "<META HTTP-EQUIV='refresh' CONTENT='3;URL=addproduct_uploadimage.php'>";
    }

    //OTHERWISE, PROCEED
    else
    {
        //EXPLAIN CURRENT PROCESS TO USER
        echo "<p>File Uploaded: " . $_FILES["file"]["name"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Temporary file stored in: " . $_FILES["file"]["tmp_name"] . "</p><br /><br />";

        //ABSOLUTE PATH OF FILE
        $img_url = "/home/space_/hybridtempo.net/images/uploads/" . $_FILES["file"]["name"];

        //IF FILE ALREADY EXISTS, TELL THE USER IT ALREADY EXISTS, REDIRECT TO TRY AGAIN
        if (file_exists($img_url))
        {
            echo "<p>" . $_FILES["file"]["name"] . " already exists. Redirecting...
            <br />
            <br />
            If you are not automatically redirected after 3 seconds, <b><a href='addproduct_uploadimage.php'>click here to try another upload.</a></p>";

            echo "<META HTTP-EQUIV='refresh' CONTENT='3;URL=addproduct_uploadimage.php'>";
        }

        //IF FILE DOES NOT ALREADY EXIST, PROCEED...
        else
        {
            //POSITION - FROM THE ABSOLUTE ROOT OF THE CLIENT'S WEBSPACE - FOR THE FILE TO GET STORED
            $img_url                =   "/home/space_/hybridtempo.net/images/uploads/" . $_FILES["file"]["name"];                       
            $thumb_url              =   "/home/space_/hybridtempo.net/images/uploads/thumbnails/" . $_FILES["file"]["name"];    

            //MOVE TEMPORARY FILE TO WHERE IT IT SHOULD BE STORED
            move_uploaded_file($_FILES["file"]["tmp_name"], $img_url);

            // FIND IMAGE WIDTH AND HEIGHT TO DETRMINE RESIZE DIMENSIONS
            list($width, $height) = getimagesize($img_url);

            // RESIZE BASED ON PORTRAIT OR LANDSCAPE ORIENTATION OF IMAGE
            if ($width > $height)
            {
                smart_resize_image($img_url,
                                      $width              = 800, 
                                      $height             = 0, 
                                      $proportional       = true, 
                                      $output             = 'file', 
                                      $delete_original    = true, 
                                      $use_linux_commands = false );


                    // STORE URL OF IMAGE IN 'picture' TABLE in 'shop' DATABASE
                    mysql_connect("**************","***********","*****");  
                    mysql_select_db("hybridtempo_shop");
                    $prod_id = $_SESSION["prod_id"];
                    $result = mysql_query ("INSERT INTO picture (prod_id,picture_url,picture_id) VALUES ('$prod_id', '$img_url', 'NULL')");
                    mysql_close();                  


                smart_resize_image($img_url,
                                      $width              = 175, 
                                      $height             = 117, 
                                      $proportional       = false, 
                                      $output             = $thumb_url, 
                                      $delete_original    = false, 
                                      $use_linux_commands = false );


                    // STORE URL OF IMAGE IN 'picture' TABLE in 'shop' DATABASE
                    mysql_connect("******************","****************","***********"); 
                    mysql_select_db("hybridtempo_shop");
                    $prod_id = $_SESSION["prod_id"];
                    $result = mysql_query ("INSERT INTO picture (prod_id,thumbnail_url,picture_id) VALUES ('$prod_id', '$thumb_url', 'NULL')");
                    mysql_close();
            }                         

            else
            {
                smart_resize_image($img_url,
                                      $width              = 0, 
                                      $height             = 700, 
                                      $proportional       = true, 
                                      $output             = 'file', 
                                      $delete_original    = true, 
                                      $use_linux_commands = false ); 


                    // STORE URL OF IMAGE IN 'picture' TABLE in 'shop' DATABASE
                    mysql_connect("*********","**********","**********"); 
                    mysql_select_db("hybridtempo_shop");
                    $prod_id = $_SESSION["prod_id"];
                    $result = mysql_query ("INSERT INTO picture (prod_id,picture_url,picture_id) VALUES ('$prod_id', '$img_url', 'NULL')");
                    mysql_close();                    


                    $wrongsize_thumb_url    =   $_FILES["file"]["name"];

                    smart_resize_image  ($img_url,
                                        $width              = 175, 
                                        $height             = 0, 
                                        $proportional       = true, 
                                        $output             = $wrongsize_thumb_url, 
                                        $delete_original    = false, 
                                        $use_linux_commands = false 
                                        );


                    //FUNCTION FROM WIDELY SUPPORTED GD LIBRARY, BUNDLED WITH PHP

                    $wrongsize_thumb_url    =   $_FILES["file"]["name"];

                    //CROP PORTRAIT THUMBNAILS, AS THEY ARE TOO TALL.


                    $image_for_resize   =   ImageCreateFromJpeg($wrongsize_thumb_url);

                    $temporary_image    =   imagecreatetruecolor(117,175);

                    imagecopyresized    (
                                        $temporary_image, $image_for_resize,
                                        $destination_x_coordinate       =   0,
                                        $destination_y_coordinate       =   0,
                                        $source_x_coordinate            =   0,
                                        $source_y_coordinate            =   58,
                                        $destination_width              =   175,
                                        $destination_height             =   117,
                                        $source_width                   =   175,
                                        $source_height                  =   261
                                        );

                    imagejpeg       ($image_for_resize, 'thumbnail_' . $_FILES["file"]["name"]);

                    imagedestroy    ($wrongsize_thumb_url);


                    // STORE URL OF IMAGE IN 'picture' TABLE in 'shop' DATABASE
                    mysql_connect("************","*************","***************"); 
                    mysql_select_db("hybridtempo_shop");
                    $prod_id = $_SESSION["prod_id"];
                    $result = mysql_query ("INSERT INTO picture (prod_id,thumbnail_url,picture_id) VALUES ('$prod_id', '$thumb_url', 'NULL')");
                    mysql_close();  
            }


            //EXPLAIN WHERE IMAGE AND THUMBNAIL WERE STORED AND INFORM OF IMINENT REDIRECT
            echo "<p>Image stored in: " . $_img_url;
            echo "<br />";
            echo "<p>Thumbnail stored in: " . $thumb_url;
            echo "<br /><br />";

            // UNSET PROD_ID VARIABLE TO PREVENT MIXUPS IF ADDING ANOTHER PRODUCT
            unset($_SESSION['prod_id']);

            //REDIRECTION MESSAGE
            echo "If you are not automatically redirected after 5 seconds, <b><a href='index.php'>click here to return to the homepage.</a></p>";

            //REDIRECT TO HOMEPAGE
            //echo "<META HTTP-EQUIV='refresh' CONTENT='5;URL=index.php'>";


        }
    }
}
else
    {
    echo "<p>Error: The file needs to be an image. Redirecting...
    <br />
    <br />
    If you are not automatically redirected after 3 seconds, <b><a href='addproduct_uploadimage.php'>click here to try another upload.</a></b></p>";
    //REDIRECT
    echo "<META HTTP-EQUIV='refresh' CONTENT='3;URL=addproduct_uploadimage.php'>";
    }
?>

 

Link to comment
Share on other sites

Here is a function I have used previously to "fit" an image to a fixed size. It will size the image to fit the available space in both dimensions and the dimension with excess information is cropped. Should work for you.

 

//This function resizes and crops an image to completely FIT into a specified size
function fitImageToSize($filename, $width_new, $height_new)
{
    $src_x  = 0;
    $src_y  = 0;

    //Get dimensions of original image
    list($width_old, $height_old) = getimagesize($filename);

    //Resize & crop image based on smallest ratio
    if ( ($width_old/$height_old) < ($width_new/$height_new) )
    {
        //Determine Resize ratio on width
        $ratio = $width_new / $width_old;
        //Detemine cropping dimensions for height
        $crop =  $height_old - ($height_new/$ratio) ;
        $height_old = $height_old - $crop;
        $src_y = floor($crop/2);
    }
    else
    {
        //Detemine Resize ratio on height
        $ratio = $height_new / $height_old;
        //Detemine cropping dimensions for width
        $crop = $width_old - ($width_new/$ratio);
        $width_old = $width_old - $crop;
        $src_x = floor($crop/2);
    }

    $image_old = imagecreatefromjpeg($filename);
    $image_new = imagecreatetruecolor($width_new, $height_new);
    imagecopyresampled($image_new, $image_old, 0, 0, $src_x, $src_y, $width_new, $height_new, $width_old, $height_old);
    return $image_new;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.