PageRenderTime 57ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/upload_crop.php

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