Advertisement
redo

Upload_crop_images

Apr 17th, 2014
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 14.75 KB | None | 0 0
  1. <?php
  2. /* http://ilkomunived.blogspot.com/2014/04/crop-imageuploadand-save.html
  3. * http://ilkomunived.blogspot.com
  4. */
  5. error_reporting (E_ALL ^ E_NOTICE);
  6. session_start(); //Do not remove this
  7. //only assign a new timestamp if the session variable is empty
  8. if (!isset($_SESSION['random_key']) || strlen($_SESSION['random_key'])==0){
  9.     $_SESSION['random_key'] = strtotime(date('Y-m-d H:i:s')); //assign the timestamp to the session variable
  10.     $_SESSION['user_file_ext']= "";
  11. }
  12. #########################################################################################################
  13. # CONSTANTS                                                                                             #
  14. # You can alter the options below                                                                       #
  15. #########################################################################################################
  16. $upload_dir = "upload_pic";                 // The directory for the images to be saved in
  17. $upload_path = $upload_dir."/";             // The path to where the image will be saved
  18. $large_image_prefix = "resize_";            // The prefix name to large image
  19. $thumb_image_prefix = "thumbnail_";         // The prefix name to the thumb image
  20. $large_image_name = $large_image_prefix.$_SESSION['random_key'];     // New name of the large image (append the timestamp to the filename)
  21. $thumb_image_name = $thumb_image_prefix.$_SESSION['random_key'];     // New name of the thumbnail image (append the timestamp to the filename)
  22. $max_file = "3";                            // Maximum file size in MB
  23. $max_width = "500";                         // Max width allowed for the large image
  24. $thumb_width = "100";                       // Width of thumbnail image
  25. $thumb_height = "100";                      // Height of thumbnail image
  26. // Only one of these image types should be allowed for upload
  27. $allowed_image_types = array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",'image/x-png'=>"png",'image/gif'=>"gif");
  28. $allowed_image_ext = array_unique($allowed_image_types); // do not change this
  29. $image_ext = "";    // initialise variable, do not change this.
  30. foreach ($allowed_image_ext as $mime_type => $ext) {
  31.     $image_ext.= strtoupper($ext)." ";
  32. }
  33.  
  34.  
  35. ##########################################################################################################
  36. # IMAGE FUNCTIONS                                                                                        #
  37. # You do not need to alter these functions                                                               #
  38. ##########################################################################################################
  39. function resizeImage($image,$width,$height,$scale) {
  40.     list($imagewidth, $imageheight, $imageType) = getimagesize($image);
  41.     $imageType = image_type_to_mime_type($imageType);
  42.     $newImageWidth = ceil($width * $scale);
  43.     $newImageHeight = ceil($height * $scale);
  44.     $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
  45.     switch($imageType) {
  46.         case "image/gif":
  47.             $source=imagecreatefromgif($image);
  48.             break;
  49.         case "image/pjpeg":
  50.         case "image/jpeg":
  51.         case "image/jpg":
  52.             $source=imagecreatefromjpeg($image);
  53.             break;
  54.         case "image/png":
  55.         case "image/x-png":
  56.             $source=imagecreatefrompng($image);
  57.             break;
  58.     }
  59.     imagecopyresampled($newImage,$source,0,0,0,0,$newImageWidth,$newImageHeight,$width,$height);
  60.    
  61.     switch($imageType) {
  62.         case "image/gif":
  63.             imagegif($newImage,$image);
  64.             break;
  65.         case "image/pjpeg":
  66.         case "image/jpeg":
  67.         case "image/jpg":
  68.             imagejpeg($newImage,$image,90);
  69.             break;
  70.         case "image/png":
  71.         case "image/x-png":
  72.             imagepng($newImage,$image);  
  73.             break;
  74.     }
  75.    
  76.     chmod($image, 0777);
  77.     return $image;
  78. }
  79. //You do not need to alter these functions
  80. function resizeThumbnailImage($thumb_image_name, $image, $width, $height, $start_width, $start_height, $scale){
  81.     list($imagewidth, $imageheight, $imageType) = getimagesize($image);
  82.     $imageType = image_type_to_mime_type($imageType);
  83.    
  84.     $newImageWidth = ceil($width * $scale);
  85.     $newImageHeight = ceil($height * $scale);
  86.     $newImage = imagecreatetruecolor($newImageWidth,$newImageHeight);
  87.     switch($imageType) {
  88.         case "image/gif":
  89.             $source=imagecreatefromgif($image);
  90.             break;
  91.         case "image/pjpeg":
  92.         case "image/jpeg":
  93.         case "image/jpg":
  94.             $source=imagecreatefromjpeg($image);
  95.             break;
  96.         case "image/png":
  97.         case "image/x-png":
  98.             $source=imagecreatefrompng($image);
  99.             break;
  100.     }
  101.     imagecopyresampled($newImage,$source,0,0,$start_width,$start_height,$newImageWidth,$newImageHeight,$width,$height);
  102.     switch($imageType) {
  103.         case "image/gif":
  104.             imagegif($newImage,$thumb_image_name);
  105.             break;
  106.         case "image/pjpeg":
  107.         case "image/jpeg":
  108.         case "image/jpg":
  109.             imagejpeg($newImage,$thumb_image_name,90);
  110.             break;
  111.         case "image/png":
  112.         case "image/x-png":
  113.             imagepng($newImage,$thumb_image_name);  
  114.             break;
  115.     }
  116.     chmod($thumb_image_name, 0777);
  117.     return $thumb_image_name;
  118. }
  119. //You do not need to alter these functions
  120. function getHeight($image) {
  121.     $size = getimagesize($image);
  122.     $height = $size[1];
  123.     return $height;
  124. }
  125. //You do not need to alter these functions
  126. function getWidth($image) {
  127.     $size = getimagesize($image);
  128.     $width = $size[0];
  129.     return $width;
  130. }
  131.  
  132. //Image Locations
  133. $large_image_location = $upload_path.$large_image_name.$_SESSION['user_file_ext'];
  134. $thumb_image_location = $upload_path.$thumb_image_name.$_SESSION['user_file_ext'];
  135.  
  136. //Create the upload directory with the right permissions if it doesn't exist
  137. if(!is_dir($upload_dir)){
  138.     mkdir($upload_dir, 0777);
  139.     chmod($upload_dir, 0777);
  140. }
  141.  
  142. //Check to see if any images with the same name already exist
  143. if (file_exists($large_image_location)){
  144.     if(file_exists($thumb_image_location)){
  145.         $thumb_photo_exists = "<img src=\"".$upload_path.$thumb_image_name.$_SESSION['user_file_ext']."\" alt=\"Thumbnail Image\"/>";
  146.     }else{
  147.         $thumb_photo_exists = "";
  148.     }
  149.     $large_photo_exists = "<img src=\"".$upload_path.$large_image_name.$_SESSION['user_file_ext']."\" alt=\"Large Image\"/>";
  150. } else {
  151.     $large_photo_exists = "";
  152.     $thumb_photo_exists = "";
  153. }
  154.  
  155. if (isset($_POST["upload"])) {
  156.     //Get the file information
  157.     $userfile_name = $_FILES['image']['name'];
  158.     $userfile_tmp = $_FILES['image']['tmp_name'];
  159.     $userfile_size = $_FILES['image']['size'];
  160.     $userfile_type = $_FILES['image']['type'];
  161.     $filename = basename($_FILES['image']['name']);
  162.     $file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));
  163.    
  164.     //Only process if the file is a JPG, PNG or GIF and below the allowed limit
  165.     if((!empty($_FILES["image"])) && ($_FILES['image']['error'] == 0)) {
  166.        
  167.         foreach ($allowed_image_types as $mime_type => $ext) {
  168.             //loop through the specified image types and if they match the extension then break out
  169.             //everything is ok so go and check file size
  170.             if($file_ext==$ext && $userfile_type==$mime_type){
  171.                 $error = "";
  172.                 break;
  173.             }else{
  174.                 $error = "Only <strong>".$image_ext."</strong> images accepted for upload<br />";
  175.             }
  176.         }
  177.         //check if the file size is above the allowed limit
  178.         if ($userfile_size > ($max_file*1048576)) {
  179.             $error.= "Images must be under ".$max_file."MB in size";
  180.         }
  181.        
  182.     }else{
  183.         $error= "Select an image for upload";
  184.     }
  185.     //Everything is ok, so we can upload the image.
  186.     if (strlen($error)==0){
  187.        
  188.         if (isset($_FILES['image']['name'])){
  189.             //this file could now has an unknown file extension (we hope it's one of the ones set above!)
  190.             $large_image_location = $large_image_location.".".$file_ext;
  191.             $thumb_image_location = $thumb_image_location.".".$file_ext;
  192.            
  193.             //put the file ext in the session so we know what file to look for once its uploaded
  194.             $_SESSION['user_file_ext']=".".$file_ext;
  195.            
  196.             move_uploaded_file($userfile_tmp, $large_image_location);
  197.             chmod($large_image_location, 0777);
  198.            
  199.             $width = getWidth($large_image_location);
  200.             $height = getHeight($large_image_location);
  201.             //Scale the image if it is greater than the width set above
  202.             if ($width > $max_width){
  203.                 $scale = $max_width/$width;
  204.                 $uploaded = resizeImage($large_image_location,$width,$height,$scale);
  205.             }else{
  206.                 $scale = 1;
  207.                 $uploaded = resizeImage($large_image_location,$width,$height,$scale);
  208.             }
  209.             //Delete the thumbnail file so the user can create a new one
  210.             if (file_exists($thumb_image_location)) {
  211.                 unlink($thumb_image_location);
  212.             }
  213.         }
  214.         //Refresh the page to show the new uploaded image
  215.         header("location:".$_SERVER["PHP_SELF"]);
  216.         exit();
  217.     }
  218. }
  219.  
  220. if (isset($_POST["upload_thumbnail"]) && strlen($large_photo_exists)>0) {
  221.     //Get the new coordinates to crop the image.
  222.     $x1 = $_POST["x1"];
  223.     $y1 = $_POST["y1"];
  224.     $x2 = $_POST["x2"];
  225.     $y2 = $_POST["y2"];
  226.     $w = $_POST["w"];
  227.     $h = $_POST["h"];
  228.     //Scale the image to the thumb_width set above
  229.     $scale = $thumb_width/$w;
  230.     $cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
  231.     //Reload the page again to view the thumbnail
  232.     header("location:".$_SERVER["PHP_SELF"]);
  233.     exit();
  234. }
  235.  
  236.  
  237. if ($_GET['a']=="delete" && strlen($_GET['t'])>0){
  238. //get the file locations
  239.     $large_image_location = $upload_path.$large_image_prefix.$_GET['t'];
  240.     $thumb_image_location = $upload_path.$thumb_image_prefix.$_GET['t'];
  241.     if (file_exists($large_image_location)) {
  242.         unlink($large_image_location);
  243.     }
  244.     if (file_exists($thumb_image_location)) {
  245.         unlink($thumb_image_location);
  246.     }
  247.     header("location:".$_SERVER["PHP_SELF"]);
  248.     exit();
  249. }
  250. ?>
  251. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  252. <html xmlns="http://www.w3.org/1999/xhtml">
  253. <head>
  254.     <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  255.     <meta name="generator" content="WebMotionUK" />
  256.     <title>WebMotionUK - PHP &amp; Jquery image upload &amp; crop</title>
  257.     <script type="text/javascript" src="js/jquery-pack.js"></script>
  258.     <script type="text/javascript" src="js/jquery.imgareaselect.min.js"></script>
  259. </head>
  260. <body>
  261. <!--
  262. * Copyright (c) 2008 http://www.webmotionuk.com / http://www.webmotionuk.co.uk
  263. * Date: 2008-11-21
  264. * "PHP & Jquery image upload & crop"
  265. * Ver 1.2
  266. * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  267. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  268. *
  269. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  270. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  271. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  272. * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  273. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  274. * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  275. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
  276. * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
  277. * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  278. *
  279. -->
  280. <ul>
  281.     <li><a href="http://www.webmotionuk.co.uk/php-jquery-image-upload-and-crop/">Back to project page</a></li>
  282.     <li><a href="http://www.webmotionuk.co.uk/jquery_upload_crop.zip">Download Files</a></li>
  283. </ul>
  284. <?php
  285. //Only display the javacript if an image has been uploaded
  286. if(strlen($large_photo_exists)>0){
  287.     $current_large_image_width = getWidth($large_image_location);
  288.     $current_large_image_height = getHeight($large_image_location);?>
  289. <script type="text/javascript">
  290. function preview(img, selection) {
  291.     var scaleX = <?php echo $thumb_width;?> / selection.width;
  292.     var scaleY = <?php echo $thumb_height;?> / selection.height;
  293.    
  294.     $('#thumbnail + div > img').css({
  295.         width: Math.round(scaleX * <?php echo $current_large_image_width;?>) + 'px',
  296.         height: Math.round(scaleY * <?php echo $current_large_image_height;?>) + 'px',
  297.         marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
  298.         marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
  299.     });
  300.     $('#x1').val(selection.x1);
  301.     $('#y1').val(selection.y1);
  302.     $('#x2').val(selection.x2);
  303.     $('#y2').val(selection.y2);
  304.     $('#w').val(selection.width);
  305.     $('#h').val(selection.height);
  306. }
  307.  
  308. $(document).ready(function () {
  309.     $('#save_thumb').click(function() {
  310.         var x1 = $('#x1').val();
  311.         var y1 = $('#y1').val();
  312.         var x2 = $('#x2').val();
  313.         var y2 = $('#y2').val();
  314.         var w = $('#w').val();
  315.         var h = $('#h').val();
  316.         if(x1=="" || y1=="" || x2=="" || y2=="" || w=="" || h==""){
  317.             alert("You must make a selection first");
  318.             return false;
  319.         }else{
  320.             return true;
  321.         }
  322.     });
  323. });
  324.  
  325. $(window).load(function () {
  326.     $('#thumbnail').imgAreaSelect({ aspectRatio: '1:<?php echo $thumb_height/$thumb_width;?>', onSelectChange: preview });
  327. });
  328.  
  329. </script>
  330. <?php }?>
  331. <h1>Photo Upload and Crop</h1>
  332. <?php
  333. //Display error message if there are any
  334. if(strlen($error)>0){
  335.     echo "<ul><li><strong>Error!</strong></li><li>".$error."</li></ul>";
  336. }
  337. if(strlen($large_photo_exists)>0 && strlen($thumb_photo_exists)>0){
  338.     echo $large_photo_exists."&nbsp;".$thumb_photo_exists;
  339.     echo "<p><a href=\"".$_SERVER["PHP_SELF"]."?a=delete&t=".$_SESSION['random_key'].$_SESSION['user_file_ext']."\">Delete images</a></p>";
  340.     echo "<p><a href=\"".$_SERVER["PHP_SELF"]."\">Upload another</a></p>";
  341.     //Clear the time stamp session and user file extension
  342.     $_SESSION['random_key']= "";
  343.     $_SESSION['user_file_ext']= "";
  344. }else{
  345.         if(strlen($large_photo_exists)>0){?>
  346.         <h2>Create Thumbnail</h2>
  347.         <div align="center">
  348.             <img src="<?php echo $upload_path.$large_image_name.$_SESSION['user_file_ext'];?>" style="float: left; margin-right: 10px;" id="thumbnail" alt="Create Thumbnail" />
  349.             <div style="border:1px #e5e5e5 solid; float:left; position:relative; overflow:hidden; width:<?php echo $thumb_width;?>px; height:<?php echo $thumb_height;?>px;">
  350.                 <img src="<?php echo $upload_path.$large_image_name.$_SESSION['user_file_ext'];?>" style="position: relative;" alt="Thumbnail Preview" />
  351.             </div>
  352.             <br style="clear:both;"/>
  353.             <form name="thumbnail" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
  354.                 <input type="hidden" name="x1" value="" id="x1" />
  355.                 <input type="hidden" name="y1" value="" id="y1" />
  356.                 <input type="hidden" name="x2" value="" id="x2" />
  357.                 <input type="hidden" name="y2" value="" id="y2" />
  358.                 <input type="hidden" name="w" value="" id="w" />
  359.                 <input type="hidden" name="h" value="" id="h" />
  360.                 <input type="submit" name="upload_thumbnail" value="Save Thumbnail" id="save_thumb" />
  361.             </form>
  362.         </div>
  363.     <hr />
  364.     <?php   } ?>
  365.     <h2>Upload Photo</h2>
  366.     <form name="photo" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post">
  367.     Photo <input type="file" name="image" size="30" /> <input type="submit" name="upload" value="Upload" />
  368.     </form>
  369. <?php } ?>
  370. <!-- Copyright (c) 2008 http://www.webmotionuk.com -->
  371. </body>
  372. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement