File upload: Resize image and reposition on new canvas


/ Published in: PHP
Save to your folder(s)

Resize and image to fit a predetermined canvas size


Copy this code and paste it in your HTML
  1. // NOW UPLOAD THE LOGO
  2.  
  3. $formname = 'CompanyLogo';
  4.  
  5. if(isset($_FILES[$formname]['name'])){
  6. $name = stripslashes($_FILES[$formname]['name']);
  7.  
  8. if ($name!=""){
  9.  
  10. $name = str_replace(" ", "_" , $name) ;
  11.  
  12. //if(move_uploaded_file($_FILES[$formname]['tmp_name'], "../images_cms/{$name}")){
  13.  
  14.  
  15. $extension = getExtension($name);
  16. $extension = strtolower($extension);
  17. if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
  18. echo ' Unknown Image extension ';
  19. $errors=1;
  20.  
  21. }else{
  22.  
  23. $size=filesize($_FILES[$formname]['tmp_name']);
  24.  
  25. //if ($size > MAX_SIZE*1024){
  26. //echo "You have exceeded the size limit";
  27. //$errors=1;
  28. //}
  29.  
  30. if($extension=="jpg" || $extension=="jpeg" ){
  31. $uploadedfile = $_FILES[$formname]['tmp_name'];
  32. $src = imagecreatefromjpeg($uploadedfile);
  33. }else if($extension=="png"){
  34. $uploadedfile = $_FILES[$formname]['tmp_name'];
  35. $src = imagecreatefrompng($uploadedfile);
  36. }else{
  37. $src = imagecreatefromgif($uploadedfile);
  38. }
  39.  
  40. list($width,$height)=getimagesize($uploadedfile);
  41.  
  42. $canvasW = 230 ;
  43. $canvasH = 78 ;
  44.  
  45. $newwidth = $canvasW;
  46. $newheight = ($height/$width)*$newwidth;
  47.  
  48. // IF THE PROPOTIONS ARE WRONG
  49.  
  50. if ($newheight > $canvasH) {
  51.  
  52. $newheight = $canvasH;
  53. $newwidth=($width/$height)*$newheight;
  54.  
  55. }
  56.  
  57. $offsetY = intval( ($canvasH-$newheight)/2 );
  58.  
  59. $tmp=imagecreatetruecolor($canvasW,$canvasH);
  60.  
  61. $white=imagecolorallocate($tmp,255,255,255);
  62. imagefilledrectangle($tmp,0,0,$canvasW,$canvasH,$white);
  63.  
  64. // imagecopyresampled ( resource $dst_image , resource $src_image ,
  65. // int $dst_x , int $dst_y ,
  66. // int $src_x , int $src_y ,
  67. // int $dst_w , int $dst_h , int $src_w , int $src_h )
  68.  
  69. imagecopyresampled($tmp,$src,
  70. 0,$offsetY,
  71. 0,0,
  72. $newwidth,$newheight,
  73. $width,$height);
  74.  
  75. $imgPath = "../images_cms/{$name}" ;
  76.  
  77. imagejpeg($tmp,$imgPath,100);
  78.  
  79. imagedestroy($src);
  80. imagedestroy($tmp);
  81.  
  82.  
  83.  
  84. $sql_cmpy=" UPDATE `cms_companies` SET `CompanyLogo`='$name' WHERE `companyID`='$companyID' ";
  85. $result_cmpy=doSQL($sql_cmpy);
  86.  
  87. } // END if $extention
  88. } // END if $name
  89. } // END LOGO

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.