ImageCompressService.php 4.4 KB

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