ImageCompressService.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  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. if (empty($sourcePath)) {
  19. throw new Exception('源文件路径不能为空');
  20. }
  21. outFileLog($sourcePath,'upload_img','$sourcePath1');
  22. // 获取图片信息
  23. $imageInfo = getimagesize($sourcePath);
  24. outFileLog($imageInfo,'upload_img','imgInfo');
  25. if (!$imageInfo) {
  26. throw new Exception('无法获取图片信息');
  27. }
  28. $width = $imageInfo[0];
  29. $height = $imageInfo[1];
  30. $type = $imageInfo[2];
  31. outFileLog($width,'upload_img','$width');
  32. outFileLog($height,'upload_img','$height');
  33. // 如果图片尺寸已经很小,且质量要求不高,直接返回原文件
  34. if ($width <= $maxWidth && $height <= $maxHeight && $quality >= 90) {
  35. return $sourcePath;
  36. }
  37. outFileLog($sourcePath,'upload_img','$sourcePath2');
  38. // 计算新尺寸
  39. $newSize = self::calculateNewSize($width, $height, $maxWidth, $maxHeight);
  40. $newWidth = $newSize['width'];
  41. $newHeight = $newSize['height'];
  42. outFileLog($newWidth,'upload_img','$newWidth');
  43. outFileLog($newHeight,'upload_img','$newHeight');
  44. // 创建源图片资源
  45. $sourceImage = self::createImageFromType($sourcePath, $type);
  46. if (!$sourceImage) {
  47. throw new Exception('不支持的图片格式');
  48. }
  49. outFileLog($sourceImage,'upload_img','$sourceImage');
  50. // 创建新图片资源
  51. $newImage = imagecreatetruecolor($newWidth, $newHeight);
  52. outFileLog($newImage,'upload_img','$newImage');
  53. // 处理透明背景(PNG/GIF)
  54. if ($type == IMAGETYPE_PNG || $type == IMAGETYPE_GIF) {
  55. imagealphablending($newImage, false);
  56. imagesavealpha($newImage, true);
  57. $transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
  58. imagefill($newImage, 0, 0, $transparent);
  59. }
  60. // 重新采样
  61. imagecopyresampled($newImage, $sourceImage, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  62. // 生成压缩后的文件路径
  63. $compressedPath = self::generateCompressedPath($sourcePath);
  64. outFileLog($compressedPath,'upload_img','$compressedPath');
  65. // 保存压缩后的图片
  66. $result = self::saveImageByType($newImage, $compressedPath, $type, $quality);
  67. utFileLog($result,'upload_img','$result');
  68. // $imageInfo = getimagesize($result);
  69. // 释放内存
  70. imagedestroy($sourceImage);
  71. imagedestroy($newImage);
  72. return $result ? $compressedPath : false;
  73. } catch (Exception $e) {
  74. return false;
  75. }
  76. }
  77. /**
  78. * 计算新尺寸(保持宽高比)
  79. */
  80. private static function calculateNewSize($width, $height, $maxWidth, $maxHeight)
  81. {
  82. $ratio = min($maxWidth / $width, $maxHeight / $height, 1);
  83. return [
  84. 'width' => intval($width * $ratio),
  85. 'height' => intval($height * $ratio)
  86. ];
  87. }
  88. /**
  89. * 根据图片类型创建图片资源
  90. */
  91. private static function createImageFromType($path, $type)
  92. {
  93. // 检查文件是否存在
  94. if (!file_exists($path)) {
  95. throw new Exception('图片文件不存在: ' . $path);
  96. }
  97. // 检查文件是否可读
  98. if (!is_readable($path)) {
  99. throw new Exception('图片文件无法读取: ' . $path);
  100. }
  101. // 检查GD扩展
  102. if (!extension_loaded('gd')) {
  103. throw new Exception('GD扩展未安装');
  104. }
  105. outFileLog(extension_loaded('gd'),'upload_img','createImageFromType-gd');
  106. outFileLog($type,'upload_img','createImageFromType-$type');
  107. try {
  108. switch ($type) {
  109. case IMAGETYPE_JPEG:
  110. $image = imagecreatefromjpeg($path);
  111. break;
  112. case IMAGETYPE_PNG:
  113. $image = imagecreatefrompng($path);
  114. break;
  115. case IMAGETYPE_GIF:
  116. $image = imagecreatefromgif($path);
  117. break;
  118. case IMAGETYPE_WEBP:
  119. if (!function_exists('imagecreatefromwebp')) {
  120. throw new Exception('WebP格式不支持');
  121. }
  122. $image = imagecreatefromwebp($path);
  123. break;
  124. default:
  125. throw new Exception('不支持的图片格式: ' . $type);
  126. }
  127. if (!$image) {
  128. throw new Exception('创建图片资源失败,可能是内存不足或文件损坏');
  129. }
  130. outFileLog($image,'upload_img','createImageFromType-$image');
  131. return $image;
  132. } catch (Exception $e) {
  133. throw new Exception('图片处理失败: ' . $e->getMessage());
  134. }
  135. }
  136. /**
  137. * 根据图片类型保存图片
  138. */
  139. private static function saveImageByType($image, $path, $type, $quality)
  140. {
  141. switch ($type) {
  142. case IMAGETYPE_JPEG:
  143. return imagejpeg($image, $path, $quality);
  144. case IMAGETYPE_PNG:
  145. // PNG压缩级别 0-9,质量参数需要转换
  146. $pngQuality = intval((100 - $quality) / 10);
  147. return imagepng($image, $path, $pngQuality);
  148. case IMAGETYPE_GIF:
  149. return imagegif($image, $path);
  150. case IMAGETYPE_WEBP:
  151. return imagewebp($image, $path, $quality);
  152. default:
  153. return false;
  154. }
  155. }
  156. /**
  157. * 生成压缩后的文件路径
  158. */
  159. private static function generateCompressedPath($originalPath)
  160. {
  161. $pathInfo = pathinfo($originalPath);
  162. return $pathInfo['dirname'] . '/' . $pathInfo['filename'] . '_compressed.' . $pathInfo['extension'];
  163. }
  164. }