Solved

Image upload & resize script needs looking at.

Posted on 2010-08-23
4
304 Views
Last Modified: 2013-12-13
hey guys,

The below code resizes images of upload to different sizes for my site.

The issue is 1) its not very neat ... could this be made more compact.

2) the images dont always resize correctly... if its 30x30 it does not always show 30x30
<?php 

error_reporting(E_ALL); 

session_start();

require_once '../settings.php';

include "../info.php"; // sets username/id ect

?><form action="<?php echo $_server['php-self'];  ?>" method="post" enctype="multipart/form-data" id="something" class="uniForm">

        <input name="new_image" id="new_image" size="30" type="file" class="fileUpload" />

        <button name="submit" type="submit" class="submitButton">Upload/Resize Image</button>

</form>

<?php

        if(isset($_POST['submit'])){

          if (isset ($_FILES['new_image'])){

                                  $file_name = $_FILES['new_image']['name'];

                                $getExt = explode ('.', $file_name);

                $file_ext = $getExt[count($getExt)-1];

                                // Adding extension verification

                                $//reads the name of the file the user submitted for uploading

 	$image=$_FILES['image']['name'];

 	//if it is not empty

 	if ($image) 

 	{

 	//get the original name of the file from the clients machine

 		$filename = stripslashes($_FILES['image']['name']);

 	//get the extension of the file in a lower case format

  		$extension = getExtension($filename);

 		$extension = strtolower($extension);

 	//if it is not a known extension, we will suppose it is an error and will not  upload the file,  

	//otherwise we will do more tests

 if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) 

 		{

		//print error message

 			echo '<h1>Unknown extension!</h1>';

 			$errors=1;

 		}        

        else

        {

                                // End extension verification           

                                $imagename = "$id.$file_ext";

                                

              $source = $_FILES['new_image']['tmp_name'];

              $target = "images/$id.$file_ext";

                          

              move_uploaded_file($source, $target);

 

              $imagepath = $imagename;

              $save = "images/thumbs/" . $imagepath; //This is the new file you saving

              $file = "images/" . $imagepath; //This is the original file

 

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

 

              // Adding proportionate image resizing, with max values

                          

                          /*

                          $modwidth = 200; 

 

              $diff = $width / $modwidth;

 

              $modheight = $height / $diff; 

              */

                          

                          $max_w = 200;

                          $max_h = 200;

                          

                          if($width <= $max_w && $height <= $max_h){ // if it fits

                     $modheight = $height; 

                                 $modwidth = $width;

                          }else{ // Then resize

                                $diff = ($width > $height) ? ($width/$max_w) :  ($height/$max_h); // Check which is bigger, and fit it to that max value. This will prevent stretching (80x800)

                    $modheight = $height / $diff; 

                                $modwidth = $width / $diff;

                          }

                          

                          // End 

                          

                          $tn = imagecreatetruecolor($modwidth, $modheight) ; 

              $image = imagecreatefromjpeg($file) ; 

              imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; 

                          imagejpeg($tn, $save, 100) ; 

 

              $imagepath = $imagename;

              $save = "images/mini/" . $imagepath; //This is the new file you saving

              $file = "images/" . $imagepath; //This is the original file

 

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

 

              $modwidth = 80; 

 

              $diff = $width / $modwidth;

 

              $modheight = $height / $diff; 

              $tn = imagecreatetruecolor($modwidth, $modheight) ; 

              $image = imagecreatefromjpeg($file) ; 

              imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ;  

 

              imagejpeg($tn, $save, 100) ; 

                          

                          

                          $imagepath = $imagename;

              $save = "images/tiny/" . $imagepath; //This is the new file you saving

              $file = "images/" . $imagepath; //This is the original file

 

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

 

              $modwidth = 40; 

 

              $diff = $width / $modwidth;

 

              $modheight = $height / $diff; 

              $tn = imagecreatetruecolor($modwidth, $modheight) ; 

              $image = imagecreatefromjpeg($file) ; 

              imagecopyresampled($tn, $image, 0, 0, 0, 0, $modwidth, $modheight, $width, $height) ; 

 

              imagejpeg($tn, $save, 100) ; 

                          $sql = "UPDATE `users` SET image = '".$id.".".$file_ext."' WHERE ID=$id";

mysql_query($sql) or die(mysql_error());

                          

            echo "Large image: <img src='images/thumbs/".$imagepath."'><br>"; 

            echo "MINI: <img src='images/mini/".$imagepath."'>"; 

                        echo "TINY: <img src='images/tiny/".$imagepath."'><br>";  

 

          }

       }}}

?>

Open in new window

0
Comment
Question by:runnerjp2005
  • 2
4 Comments
 
LVL 11

Accepted Solution

by:
Rajesh Dalmia earned 500 total points
ID: 33499987
0
 

Author Comment

by:runnerjp2005
ID: 33500428
im looking @ the above link but its very unclear how to use it
0
 
LVL 11

Expert Comment

by:Rajesh Dalmia
ID: 33500469
you have to download the class file from that site...
can use below code (with modification) to upload file
$handle = new upload($_FILES['image_field']);

   if ($handle->uploaded) {

       $handle->file_new_name_body   = 'image_resized';  //you can give new file name

       $handle->image_resize         = true;   //this will resize the file

       $handle->image_x              = 100;  //those 2 are for image resize ratio

       $handle->image_ratio_y        = true;

       $handle->process('/home/user/files/');  //this is path where file will be save

       if ($handle->processed) {

           echo 'image resized';

           $handle->clean();

       } else {

           echo 'error : ' . $handle->error;

       }

   }

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 33501688
Here is a script that teaches how to do it.  Please read it over -- code, comments and man page references -- then post back here if you have any questions.  Best of luck with your project, ~Ray
<?php // RAY_upload_and_resize_image.php 


// UPLOAD AN IMAGE AND RESIZE IT TO FIT A PREDEFINED SIZE


// A FUNCTION TO DETERMINE IF GD IS AT LEVEL 2 OR MORE
function get_gd_info($display=FALSE)
{

// IS GD INSTALLED AT ALL?
   if (!function_exists("gd_info"))
   {
      if ($display) echo "<br/>GD NOT INSTALLED\n";
      return FALSE;
   }

// IF GD IS INSTALLED GET DETAILS
   $gd = gd_info();

// IF DISPLAY IS REQUESTED, PRINT DETAILS
   if ($display)
   {
      echo "<br/>GD DETAILS:\n";
      foreach ($gd as $key => $value)
      {
         if ($value === TRUE)  $value = 'YES';
         if ($value === FALSE) $value = 'NO';
         echo "<br/>$key = $value \n";
      }
   }

// RETURN THE VERSION NUMBER
   $gd_version = preg_replace('/[^0-9\.]/', '', $gd["GD Version"]);
   return $gd_version;
}


// A FUNCTION TO MAKE AN IMAGE INTO THE RIGHT WIDTH FOR PAGE DISPLAY
// WILL WORK IF GD2 NOT INSTALLED, BUT WILL MAKE BETTER IMAGES WITH GD2
// INPUT IS THE IMAGE FILE NAME, OUTPUT IS AN IMAGE RESOURCE, OR FALSE IF NO RESIZE NEEDED
function create_right_size_image($image, $width=720)
{
// IS GD HERE?
   $gdv = get_gd_info();
   if (!$gdv) return FALSE;

// GET AN IMAGE THING
   $source = imagecreatefromjpeg("$image");

// GET THE X AND Y DIMENSIONS
   $imageX = imagesx($source);
   $imageY = imagesy($source);

// IF NO RESIZING IS NEEDED
   if ($imageX <= $width)
   {
      return FALSE;
   }

// THE WIDTH IS TOO GREAT - MUST RESIZE
   $tnailX = $width;
   $tnailY = (int) (($tnailX * $imageY) / $imageX );

// WHICH FUNCTIONS CAN RESIZE / RESAMPLE THE IMAGE?
   if ($gdv >= 2)
   {
// IF GD IS AT LEVEL 2 OR ABOVE
      $target = imagecreatetruecolor($tnailX, $tnailY);
      imagecopyresampled ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
   } else
   {
// IF GD IS AT A LOWER REVISION LEVEL
      $target = imagecreate($tnailX, $tnailY);
      imagecopyresized   ($target, $source, 0, 0, 0, 0, $tnailX, $tnailY, $imageX, $imageY);
   }
   return $target ;
}
/* ********************************************************************************************* */


// ESTABLISH THE NAME OF THE PHOTOS DIRECTORY
$photos    = 'photos';

// ESTABLISH THE LARGEST FILE WE WILL UPLOAD
$max_file_size = '5000000'; // A BIT MORE THAN 4MB

// THIS IS A LIST OF THE POSSIBLE ERRORS THAT CAN BE REPORTED in $_FILES[]["error"]
$errors    = array(
    0=>"Success!",
    1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
    2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
    3=>"The uploaded file was only partially uploaded",
    4=>"No file was uploaded",
    6=>"Missing a temporary folder",
    7=>"Cannot write file to disk"
);

// IF THERE IS NOTHING USEFUL IN $_POST, PUT UP THE FORM FOR INPUT
if ( (empty($_POST['p'])) && (empty($_POST['MAX_FILE_SIZE'])) ) {
    ?>
    <h2>Upload Photos</h2>

    <!-- ENCTYPE -->
    <form name="UploadForm" enctype="multipart/form-data" action="<?=$_SERVER["REQUEST_URI"]?>" method="POST">
    <input type="hidden" name="p" value="1" />
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="<?=$max_file_size?>" />
    <!-- INPUT NAME= IN TYPE=FILE DETERMINES THE NAME FOR ACTION SCRIPT TO USE IN $_FILES ARRAY -->
    <p>
    Find the photo you want to upload and click the "Upload" button below.
    </p>

    <table cellpadding="1" cellspacing="1" border="0">
    <tr><td align="right"><span class="required">Photo: </span></td> <td><input name="userfile" type="file" size="80" /></td></tr>
    <tr><td> </td><td><input type="submit" name="_submit" value="Upload" />
    &nbsp; &nbsp; Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> an existing photo.</td></tr>
    </table>
    </form>
    <?php

    die();

} else {

// THERE IS POST DATA - PROCESS IT
    echo "<h2>Results: Upload Photos</h2>\n";
    echo "<p>\n";

// SYNTHESIZE THE NEW FILE NAME
    $f_type    = trim(strtolower(end    (explode( '.', basename($_FILES['userfile']['name'] )))));
    $f_name    = trim(strtolower(current(explode( '.', basename($_FILES['userfile']['name'] )))));
    $my_new = getcwd() . '/' . $photos . '/' . $f_name .'.'. $f_type;
    $my_file= $photos . '/' . $f_name .'.'. $f_type;

// TEST FOR ALLOWABLE EXTENSIONS
    if ($f_type != 'jpg')
    {
       die('Sorry, only JPG files allowed');
    }

// IF THERE ARE ERRORS
    $error_code    = $_FILES["userfile"]["error"];
    if ($error_code != 0)
    {
        $error_message = $errors[$error_code];
        echo "<p class=\"required\">Upload Error Code: $error_code: $error_message</p>\n";
        die('Sorry');
    }

// MOVE THE FILE INTO THE DIRECTORY
    $overwrite    = $_POST['overwrite'];
    $file_size    = number_format($_FILES["userfile"]["size"]);

// IF THE FILE IS NEW
    if (!file_exists($my_new))
    {
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new))
        {
            $upload_success = 1;
        } else
        {
            $upload_success = -1;
        }

// IF THE FILE ALREADY EXISTS
    } else
    {
        echo "<b><i>$my_file</i></b> already exists.\n";

// SHOULD WE OVERWRITE THE FILE? IF NOT
        if (empty($overwrite))
        {
            $upload_success = 0;

// IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
        } else
        {
            $now    = date('Y-m-d');
            $my_bak = $my_new . '.' . $now . '.bak';
            if (!copy($my_new, $my_bak))
            {
                echo "<b>Attempted Backup Failed!</b>\n";
            }
            if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_new))
            {
                $upload_success = 2;
            } else
            {
                $upload_success = -1;
            }
        }
    }

// REPORT OUR SUCCESS OR FAILURE
    if ($upload_success == 2) { echo "It has been overwritten.\n"; }
    if ($upload_success == 1) { echo "<b><i>$my_file</i></b> has been saved.\n"; }
    if ($upload_success == 0) { echo "<b>It was NOT overwritten.</b>\n"; }

    if ($upload_success > 0)
    {
        echo "$file_size bytes uploaded.\n";
        chmod ($my_new, 0755);
    }

    echo "</p>\n";

// RESIZE THE FILE TO FIT PAGE WIDTH, IF NECESSARY
    if ($upload_success > 0)
    {
        if ($imageblob    = create_right_size_image($my_new))
        {
            imagejpeg($imageblob, $my_new);
        }
    }

    echo "<p><a href=\"$my_file\">See the file</a></p>\n";
}

Open in new window

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Deprecated and Headed for the Dustbin By now, you have probably heard that some PHP features, while convenient, can also cause PHP security problems.  This article discusses one of those, called register_globals.  It is a thing you do not want.  …
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to dynamically set the form action using jQuery.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

757 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now