ImageBack.php 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. class ImageBack
  3. {
  4. protected $filename;
  5. protected $fileExt = "";
  6. protected $croppedWidth = 0;
  7. protected $croppedHeight = 0;
  8. protected $width = 0;
  9. protected $height = 0;
  10. protected $croppedX = 0;
  11. protected $croppedY = 0;
  12. protected $source;
  13. protected $cropped;
  14. protected $process = true;
  15. protected $funName = "jpeg";
  16. function __construct($filename)
  17. {
  18. $this->filename = $filename;
  19. $fileExt = pathinfo($filename, PATHINFO_EXTENSION);
  20. $this->fileExt = $fileExt;
  21. switch ($this->fileExt) {
  22. case 'jpg':
  23. case 'jpeg':
  24. $this->funName = "jpeg";
  25. break;
  26. case 'png':
  27. $this->funName = 'png';
  28. break;
  29. case 'webp':
  30. $this->funName = 'webp';
  31. break;
  32. default:
  33. $this->process = false;
  34. }
  35. if ($this->process) {
  36. $fun = 'imagecreatefrom' . $this->funName;
  37. $this->source = $fun($filename);
  38. $this->width = imagesx($this->source);
  39. $this->height = imagesy($this->source);
  40. }
  41. }
  42. public function resize($croppedWidth, $croppedHeight = 0, $croppedX = 0, $croppedY = 0): ImageBack
  43. {
  44. if ($this->process) {
  45. $this->croppedHeight = $croppedHeight;
  46. $this->croppedWidth = $croppedWidth;
  47. $this->croppedX = $croppedX;
  48. $this->croppedY = $croppedY;
  49. if ($croppedWidth >= $this->width) {
  50. $this->croppedWidth = $this->width;
  51. }
  52. if ($croppedHeight == 0) {
  53. $this->croppedHeight = (int)($this->height / ($this->width / $this->croppedWidth));
  54. } else if ($croppedHeight >= $this->height) {
  55. $this->croppedHeight = $this->height;
  56. }
  57. $this->cropped = imagecreatetruecolor($this->croppedWidth, $this->croppedHeight);
  58. if ($this->funName == 'png'|| $this->funName == 'webp') {
  59. // 将图像设置为支持 alpha 通道的模式
  60. imagealphablending($this->cropped, false);
  61. imagesavealpha($this->cropped, true);
  62. $transparentColor = imagecolorallocatealpha($this->cropped, 0, 0, 0, 127);
  63. imagefill($this->cropped, 0, 0, $transparentColor);
  64. }
  65. }
  66. return $this;
  67. }
  68. public function save($savePath)
  69. {
  70. if ($this->process) {
  71. try {
  72. imagecopyresampled($this->cropped, $this->source, 0, 0, 0, 0, $this->croppedWidth, $this->croppedHeight, $this->width, $this->height);
  73. $fun = 'image' . $this->funName;
  74. $fun($this->cropped, $savePath);
  75. imagedestroy($this->source);
  76. return true;
  77. } catch (Exception $exception) {
  78. return $exception->getMessage();
  79. }
  80. }
  81. return false;
  82. }
  83. }