1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 |
function resize($maxWidth,$maxHeight, $targetFile, $originalFile) { $info = getimagesize($originalFile); $mime = $info['mime']; switch ($mime) { case 'image/jpeg': $image_create_func = 'imagecreatefromjpeg'; $image_save_func = 'imagejpeg'; $new_image_ext = 'jpg'; break; case 'image/png': $image_create_func = 'imagecreatefrompng'; $image_save_func = 'imagepng'; $new_image_ext = 'png'; break; case 'image/gif': $image_create_func = 'imagecreatefromgif'; $image_save_func = 'imagegif'; $new_image_ext = 'gif'; break; default: throw Exception('Unknown image type.'); } $img = $image_create_func($originalFile); list($origWidth, $origHeight) = getimagesize($originalFile); if ($maxWidth == 0) { $maxWidth = $origWidth; } if ($maxHeight == 0) { $maxHeight = $origHeight; } // Calculate ratio of desired maximum sizes and original sizes. $widthRatio = $maxWidth / $origWidth; $heightRatio = $maxHeight / $origHeight; // Ratio used for calculating new image dimensions. $ratio = min($widthRatio, $heightRatio); // Calculate new image dimensions. $newWidth = (int)$origWidth * $ratio; $newHeight = (int)$origHeight * $ratio; $tmp = imagecreatetruecolor($newWidth,$newHeight); if($image_save_func=='imagepng'){ imagealphablending($tmp, false); imagesavealpha($tmp,true); $transparent = imagecolorallocatealpha($tmp, 255, 255, 255, 127); imagefilledrectangle($tmp, 0, 0, $newWidth, $newHeight, $transparent); imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight,$origWidth, $origHeight); }else{ imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $origWidth, $origHeight); } if (file_exists($targetFile)) { unlink($targetFile); } $image_save_func($tmp, "$targetFile.$new_image_ext"); return $targetFile.".".$new_image_ext; } $name = explode(".",$_FILES['uploadfile']['name']); $filename = resize('150', '150', $name[0], $_FILES['uploadfile']['tmp_name']); echo "<img src='$filename'>"; echo filesize($filename); |
Leave a reply