示例#1
0
 /**
  * ฟังก์ชั่นปรับขนาดของภาพ โดยรักษาอัตราส่วนของภาพตามความกว้างที่ต้องการ
  * หากรูปภาพมีขนาดเล็กกว่าที่กำหนด จะเป็นการ copy file
  * หากรูปภาพมาความสูง หรือความกว้างมากกว่า $width
  * จะถูกปรับขนาดให้มีขนาดไม่เกิน $width (ทั้งความสูงและความกว้าง)
  * และเปลี่ยนชนิดของภาพเป็น jpg
  *
  * @param string $source path และชื่อไฟล์ของไฟล์รูปภาพต้นฉบับ
  * @param string $target path ของไฟล์รูปภาพปลายทาง
  * @param string $name ชื่อไฟล์ของรูปภาพปลายทาง
  * @param array $info [width, height, mime] ของรูปภาพ
  * @param int $width ขนาดสูงสุดของรูปภาพที่ต้องการ
  * @param string $watermark (optional) ข้อความลายน้ำ
  * @return array|boolean คืนค่าแอเรย์ [name, width, height, mime] ของรูปภาพปลายทาง หรือ false ถ้าไม่สามารถดำเนินการได้
  */
 public static function resizeImage($source, $target, $name, $info, $width, $watermark = '')
 {
     if ($info['width'] > $width || $info['height'] > $width) {
         if ($info['width'] <= $info['height']) {
             $h = $width;
             $w = round($h * $info['width'] / $info['height']);
         } else {
             $w = $width;
             $h = round($w * $info['height'] / $info['width']);
         }
         switch ($info['mime']) {
             case 'image/gif':
                 $o_im = imageCreateFromGIF($source);
                 break;
             case 'image/jpg':
             case 'image/jpeg':
             case 'image/pjpeg':
                 $o_im = gcms::orientImage($source);
                 break;
             case 'image/png':
             case 'image/x-png':
                 $o_im = imageCreateFromPNG($source);
                 break;
         }
         $o_wd = @imagesx($o_im);
         $o_ht = @imagesy($o_im);
         $t_im = @ImageCreateTrueColor($w, $h);
         @ImageCopyResampled($t_im, $o_im, 0, 0, 0, 0, $w + 1, $h + 1, $o_wd, $o_ht);
         if ($watermark != '') {
             $t_im = gcms::watermarkText($t_im, $watermark);
         }
         $newname = substr($name, 0, strrpos($name, '.')) . '.jpg';
         if (!@ImageJPEG($t_im, $target . $newname)) {
             $ret = false;
         } else {
             $ret['name'] = $newname;
             $ret['width'] = $w;
             $ret['height'] = $h;
             $ret['mime'] = 'image/jpeg';
         }
         @imageDestroy($o_im);
         @imageDestroy($t_im);
         return $ret;
     } elseif (@copy($source, $target . $name)) {
         $ret['name'] = $name;
         $ret['width'] = $info['width'];
         $ret['height'] = $info['height'];
         $ret['mime'] = $info['mime'];
         return $ret;
     }
     return false;
 }