Advertisement
Guest User

Untitled

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