ImageCompressService.php 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. <?php
  2. namespace app\common\service;
  3. use Exception;
  4. class ImageCompressService
  5. {
  6. /**
  7. * 压缩图片
  8. * @param string $sourcePath 源文件路径
  9. * @param int $quality 压缩质量 (1-100)
  10. * @param int $maxWidth 最大宽度
  11. * @param int $maxHeight 最大高度
  12. * @return string|false 压缩后的文件路径
  13. */
  14. public static function compress($sourcePath, $quality = 80, $maxWidth = 1920, $maxHeight = 1080)
  15. {
  16. try {
  17. // 获取图片信息
  18. $imageInfo = getimagesize($sourcePath);
  19. outFileLog($imageInfo,'upload_img','imgInfo');
  20. if (!$imageInfo) {
  21. throw new Exception('无法获取图片信息');
  22. }
  23. $width = $imageInfo[0];
  24. $height = $imageInfo[1];
  25. $type = $imageInfo[2];
  26. outFileLog($width,'upload_img','$width');
  27. outFileLog($height,'upload_img','$height');
  28. // 如果图片尺寸已经很小,且质量要求不高,直接返回原文件
  29. if ($width <= $maxWidth && $height <= $maxHeight && $quality >= 90) {
  30. return $sourcePath;
  31. }
  32. // 计算新尺寸
  33. $newSize = self::calculateNewSize($width, $height, $maxWidth, $maxHeight);
  34. $newWidth = $newSize['width'];
  35. $newHeight = $newSize['height'];
  36. // 创建源图片资源
  37. $sourceImage = self::createImageFromType($sourcePath, $type);
  38. if (!$sourceImage) {
  39. throw new Exception('不支持的图片格式');
  40. }
  41. // 创建新图片资源
  42. $newImage = imagecreatetruecolor($newWidth, $newHeight);
  43. // 处理透明背景(PNG/GIF)
  44. if ($type == IMAGETYPE_PNG || $type == IMAGETYPE_GIF) {
  45. imagealphablending($newImage, false);
  46. imagesavealpha($newImage, true);
  47. $transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
  48. imagefill($newImage, 0, 0, $transparent);
  49. }
  50. // 重新采样
  51. imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  52. // 生成压缩后的文件路径
  53. $compressedPath = self::generateCompressedPath($sourcePath);
  54. // 保存压缩后的图片
  55. $result = self::saveImageByType($newImage, $compressedPath, $type, $quality);
  56. // 释放内存
  57. imagedestroy($sourceImage);
  58. imagedestroy($newImage);
  59. return $result ? $compressedPath : false;
  60. } catch (Exception $e) {
  61. return false;
  62. }
  63. }
  64. /**
  65. * 计算新尺寸(保持宽高比)
  66. */
  67. private static function calculateNewSize($width, $height, $maxWidth, $maxHeight)
  68. {
  69. $ratio = min($maxWidth / $width, $maxHeight / $height, 1);
  70. return [
  71. 'width' => intval($width * $ratio),
  72. 'height' => intval($height * $ratio)
  73. ];
  74. }
  75. /**
  76. * 根据图片类型创建图片资源
  77. */
  78. private static function createImageFromType($path, $type)
  79. {
  80. switch ($type) {
  81. case IMAGETYPE_JPEG:
  82. return imagecreatefromjpeg($path);
  83. case IMAGETYPE_PNG:
  84. return imagecreatefrompng($path);
  85. case IMAGETYPE_GIF:
  86. return imagecreatefromgif($path);
  87. case IMAGETYPE_WEBP:
  88. return imagecreatefromwebp($path);
  89. default:
  90. return false;
  91. }
  92. }
  93. /**
  94. * 根据图片类型保存图片
  95. */
  96. private static function saveImageByType($image, $path, $type, $quality)
  97. {
  98. switch ($type) {
  99. case IMAGETYPE_JPEG:
  100. return imagejpeg($image, $path, $quality);
  101. case IMAGETYPE_PNG:
  102. // PNG压缩级别 0-9,质量参数需要转换
  103. $pngQuality = intval((100 - $quality) / 10);
  104. return imagepng($image, $path, $pngQuality);
  105. case IMAGETYPE_GIF:
  106. return imagegif($image, $path);
  107. case IMAGETYPE_WEBP:
  108. return imagewebp($image, $path, $quality);
  109. default:
  110. return false;
  111. }
  112. }
  113. /**
  114. * 生成压缩后的文件路径
  115. */
  116. private static function generateCompressedPath($originalPath)
  117. {
  118. $pathInfo = pathinfo($originalPath);
  119. return $pathInfo['dirname'] . '/' . $pathInfo['filename'] . '_compressed.' . $pathInfo['extension'];
  120. }
  121. }