CompressImageHandler.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Handlers;
  3. class CompressImageHandler
  4. {
  5. private $image; //重绘图片
  6. private $imageinfo; //重绘图片的具体信息(array)
  7. private $percent = 0.5; //压缩比例,1为原像素比例
  8. //接收的图片文件
  9. public function Upload()
  10. {
  11. $file = $_FILES['img'];
  12. // 要上传图片的本地路径
  13. $filePath = $file['tmp_name'];
  14. // 对图片压缩重绘
  15. $this->_openImage($filePath);
  16. // 将重绘后的图片流赋值使用
  17. ob_start(); // 开始输出缓存.
  18. $fileName = $file['name'];
  19. $ext = pathinfo($fileName, PATHINFO_EXTENSION); // 后缀
  20. if ($ext == 'jpg' || $ext == 'jpeg') {
  21. imagejpeg($this->image); // imagejpeg()通常会输出图像, 由于ob_start(), 所以不会.
  22. }
  23. if ($ext == 'png') {
  24. imagepng($this->image); // imagepng()通常会输出图像, 由于ob_start(), 所以不会.
  25. }
  26. $contents = ob_get_contents(); // 把上面的输出保存为 $content
  27. ob_end_clean(); // 结束输出缓存.
  28. imagedestroy($this->image);
  29. return $contents;
  30. }
  31. /**
  32. * 内部:打开图片
  33. */
  34. private function _openImage($src)
  35. {
  36. list($width, $height, $type, $attr) = getimagesize($src);
  37. $this->imageinfo = array(
  38. 'width' => $width,
  39. 'height' => $height,
  40. 'type' => image_type_to_extension($type, false),
  41. 'attr' => $attr
  42. );
  43. $fun = "imagecreatefrom" . $this->imageinfo['type'];
  44. $this->image = $fun($src);
  45. $this->_thumpImage();
  46. }
  47. /**
  48. * 内部:操作图片
  49. */
  50. private function _thumpImage()
  51. {
  52. $new_width = $this->imageinfo['width'] * $this->percent;
  53. $new_height = $this->imageinfo['height'] * $this->percent;
  54. $image_thump = imagecreatetruecolor($new_width, $new_height);
  55. //绘制图片透明底色
  56. imagesavealpha($image_thump, true);
  57. $black = imagecolorallocate($image_thump, 0, 0, 0);
  58. imagefilledrectangle($image_thump, 0, 0, 150, 25, $black);
  59. $trans_colour = imagecolorallocatealpha($image_thump, 0, 0, 0, 127);
  60. imagefill($image_thump, 0, 0, $trans_colour);
  61. //将原图复制带图片载体上面,并且按照一定比例压缩,极大的保持了清晰度
  62. imagecopyresampled($image_thump, $this->image, 0, 0, 0, 0, $new_width, $new_height, $this->imageinfo['width'], $this->imageinfo['height']);
  63. imagedestroy($this->image);
  64. $this->image = $image_thump;
  65. }
  66. }