1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <?php
- namespace App\Handlers;
- class CompressImageHandler
- {
- private $image; //重绘图片
- private $imageinfo; //重绘图片的具体信息(array)
- private $percent = 0.5; //压缩比例,1为原像素比例
- //接收的图片文件
- public function Upload()
- {
- $file = $_FILES['img'];
- // 要上传图片的本地路径
- $filePath = $file['tmp_name'];
- // 对图片压缩重绘
- $this->_openImage($filePath);
- // 将重绘后的图片流赋值使用
- ob_start(); // 开始输出缓存.
- $fileName = $file['name'];
- $ext = pathinfo($fileName, PATHINFO_EXTENSION); // 后缀
- if ($ext == 'jpg' || $ext == 'jpeg') {
- imagejpeg($this->image); // imagejpeg()通常会输出图像, 由于ob_start(), 所以不会.
- }
- if ($ext == 'png') {
- imagepng($this->image); // imagepng()通常会输出图像, 由于ob_start(), 所以不会.
- }
- $contents = ob_get_contents(); // 把上面的输出保存为 $content
- ob_end_clean(); // 结束输出缓存.
- imagedestroy($this->image);
- return $contents;
- }
- /**
- * 内部:打开图片
- */
- private function _openImage($src)
- {
- list($width, $height, $type, $attr) = getimagesize($src);
- $this->imageinfo = array(
- 'width' => $width,
- 'height' => $height,
- 'type' => image_type_to_extension($type, false),
- 'attr' => $attr
- );
- $fun = "imagecreatefrom" . $this->imageinfo['type'];
- $this->image = $fun($src);
- $this->_thumpImage();
- }
- /**
- * 内部:操作图片
- */
- private function _thumpImage()
- {
- $new_width = $this->imageinfo['width'] * $this->percent;
- $new_height = $this->imageinfo['height'] * $this->percent;
- $image_thump = imagecreatetruecolor($new_width, $new_height);
- //绘制图片透明底色
- imagesavealpha($image_thump, true);
- $black = imagecolorallocate($image_thump, 0, 0, 0);
- imagefilledrectangle($image_thump, 0, 0, 150, 25, $black);
- $trans_colour = imagecolorallocatealpha($image_thump, 0, 0, 0, 127);
- imagefill($image_thump, 0, 0, $trans_colour);
- //将原图复制带图片载体上面,并且按照一定比例压缩,极大的保持了清晰度
- imagecopyresampled($image_thump, $this->image, 0, 0, 0, 0, $new_width, $new_height, $this->imageinfo['width'], $this->imageinfo['height']);
- imagedestroy($this->image);
- $this->image = $image_thump;
- }
- }
|