สวัสดีครับ ในวันนี้เราจะมาแนะนำเทคนิค การ Upload ไฟล์ภาพ และ Resize เป็นไฟล์ Thumbnail ด้วย PHP ครับ
โดยในขั้นตอนของการ Resize เราจะใช้ Resize Image Class With PHP เป็น Class สำหรับการ Resize Image ครับ
มาเริ่มกันเลย ก่อนอื่นต้องมาสร้างฟอร์ม อัพโหลดกันก่อนครับ
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<!DOCTYPE html> <html> <body> <form action="upload.php" method="post" enctype="multipart/form-data"> เลือกไฟล์ภาพ <input type="file" name="fileToUpload" id="fileToUpload"> <hr> <input type="submit" value="Upload Image" name="submit"> </form> </body> </html> |
ต่อมาเรามาสร้างไฟล์ upload.php สำหรับ Upload ไฟล์ครับ
อย่าลืมสร้าง Folder uploads ด้วยนะครับใช้สำหรับเก็บไฟล์ที่เราได้ upload แล้ว
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 |
<?php include "ResizeImage.php";//นำเข้า class ResizeImage เข้ามาใช้ในไฟล์ //ตรวจสอบว่ามีการ submit ข้อมูลมาหรือไม่ if(isset($_POST["submit"]) && !empty($_FILES["fileToUpload"]["name"])) { $target_dir = "uploads/";//ชื่อ Folder สำหรับเก็บไฟล์ที่ Upload $path_parts = pathinfo($_FILES["fileToUpload"]["name"]); $extension = $path_parts['extension'];//นามสกุลไฟล์ $filename = date("YmdHis").'.'.$extension;//เปลี่ยนชื่อไฟล์ที่ upload แล้ว $target_file = $target_dir.$filename; $newFileThumbnail = $target_dir.date("YmdHis").'_thumbnail.'.$extension;//เปลี่ยนชื่อไฟล์ thumbnail ที่ ลดขนาดแล้ว if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) { $resize = new ResizeImage($target_file);//เรียกใช้งาน class สำหรับ Resize $resize->resizeTo(150, 150, 'exact');//กำหนดขนาดที่ต้องการ Resize กว้าง 150 สูง 150 $resize->saveImage($newFileThumbnail);//สร้างไฟล์ที่ลดขนาดแล้ว echo "The file ". htmlspecialchars($filename). " has been uploaded."; } else { echo "Sorry, there was an error uploading your file."; } }else{ echo "Sorry, there was an error uploading your file."; } ?> |
สร้าง Classs ResizeImage สำหรับ Resize File ที่เรา Upload ให้มีขนาดเล็กลงตามที่เรากำหนดครับ
รายละเอียดเพิ่มเติม Resize Image Class With PHP
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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
<?php /** * Resize image class will allow you to resize an image * * Can resize to exact size * Max width size while keep aspect ratio * Max height size while keep aspect ratio * Automatic while keep aspect ratio */ class ResizeImage { private $ext; private $image; private $newImage; private $origWidth; private $origHeight; private $resizeWidth; private $resizeHeight; /** * Class constructor requires to send through the image filename * * @param string $filename - Filename of the image you want to resize */ public function __construct( $filename ) { if(file_exists($filename)) { $this->setImage( $filename ); } else { throw new Exception('Image ' . $filename . ' can not be found, try another image.'); } } /** * Set the image variable by using image create * * @param string $filename - The image filename */ private function setImage( $filename ) { $size = getimagesize($filename); $this->ext = $size['mime']; switch($this->ext) { // Image is a JPG case 'image/jpg': case 'image/jpeg': // create a jpeg extension $this->image = imagecreatefromjpeg($filename); break; // Image is a GIF case 'image/gif': $this->image = @imagecreatefromgif($filename); break; // Image is a PNG case 'image/png': $this->image = @imagecreatefrompng($filename); break; // Mime type not found default: throw new Exception("File is not an image, please use another file type.", 1); } $this->origWidth = imagesx($this->image); $this->origHeight = imagesy($this->image); } /** * Save the image as the image type the original image was * * @param String[type] $savePath - The path to store the new image * @param string $imageQuality - The qulaity level of image to create * * @return Saves the image */ public function saveImage($savePath, $imageQuality="100", $download = false) { switch($this->ext) { case 'image/jpg': case 'image/jpeg': // Check PHP supports this file type if (imagetypes() & IMG_JPG) { imagejpeg($this->newImage, $savePath, $imageQuality); } break; case 'image/gif': // Check PHP supports this file type if (imagetypes() & IMG_GIF) { imagegif($this->newImage, $savePath); } break; case 'image/png': $invertScaleQuality = 9 - round(($imageQuality/100) * 9); // Check PHP supports this file type if (imagetypes() & IMG_PNG) { imagepng($this->newImage, $savePath, $invertScaleQuality); } break; } if($download) { header('Content-Description: File Transfer'); header("Content-type: application/octet-stream"); header("Content-disposition: attachment; filename= ".$savePath.""); readfile($savePath); } imagedestroy($this->newImage); } /** * Resize the image to these set dimensions * * @param int $width - Max width of the image * @param int $height - Max height of the image * @param string $resizeOption - Scale option for the image * * @return Save new image */ public function resizeTo( $width, $height, $resizeOption = 'default' ) { switch(strtolower($resizeOption)) { case 'exact': $this->resizeWidth = $width; $this->resizeHeight = $height; break; case 'maxwidth': $this->resizeWidth = $width; $this->resizeHeight = $this->resizeHeightByWidth($width); break; case 'maxheight': $this->resizeWidth = $this->resizeWidthByHeight($height); $this->resizeHeight = $height; break; default: if($this->origWidth > $width || $this->origHeight > $height) { if ( $this->origWidth > $this->origHeight ) { $this->resizeHeight = $this->resizeHeightByWidth($width); $this->resizeWidth = $width; } else if( $this->origWidth < $this->origHeight ) { $this->resizeWidth = $this->resizeWidthByHeight($height); $this->resizeHeight = $height; } } else { $this->resizeWidth = $width; $this->resizeHeight = $height; } break; } $this->newImage = imagecreatetruecolor($this->resizeWidth, $this->resizeHeight); imagecopyresampled($this->newImage, $this->image, 0, 0, 0, 0, $this->resizeWidth, $this->resizeHeight, $this->origWidth, $this->origHeight); } /** * Get the resized height from the width keeping the aspect ratio * * @param int $width - Max image width * * @return Height keeping aspect ratio */ private function resizeHeightByWidth($width) { return floor(($this->origHeight/$this->origWidth)*$width); } /** * Get the resized width from the height keeping the aspect ratio * * @param int $height - Max image height * * @return Width keeping aspect ratio */ private function resizeWidthByHeight($height) { return floor(($this->origWidth/$this->origHeight)*$height); } } ?> |
ทดสอบการทำงาน
เมื่อ Upload Image แล้ว หากไม่มีอะไรผิดพลาด ใน Folder uploads จะมีไฟล์ที่เรา Upload และ ไฟล์ที่ถูก Resize แล้วดังภาพ
ข้อขอบคุณข้อมูลจาก