PHP 生成图片 图片按照比例压缩, 图片居中背景大小固定

迈不过友情╰ 2023-05-30 08:58 105阅读 0赞

PHP 7.0
需求:上传任意大小图片,按照宽高比例压缩,生成固定大小的图片,不足的地方用白边补齐

  1. $height = $width = 400;
  2. $file_info = @getimagesize($filename);
  3. $orig_width = $file_info[0] ?? 0;
  4. $orig_height = $file_info[1] ?? 0;
  5. $file_type = $file_info['mime'] ?? '';
  6. // 生成等比例缩放图
  7. $tmp_image_width = 0;
  8. $tmp_image_height = 0;
  9. if ($orig_width / $orig_height >= $width / $height) {
  10. $tmp_image_width = $width;
  11. $tmp_image_height = round($tmp_image_width * $orig_height / $orig_width);
  12. } else {
  13. $tmp_image_height = $height;
  14. $tmp_image_width = round($tmp_image_height * $orig_width / $orig_height);
  15. }
  16. $tmp_image = imagecreatetruecolor($tmp_image_width, $tmp_image_height);
  17. $orgi_image = @imagecreatefromjpeg($filename);
  18. imagecopyresampled($tmp_image, $orgi_image, 0, 0, 0, 0, $tmp_image_width, $tmp_image_height, $orig_width, $orig_height);
  19. // 添加白色背景
  20. $final_image = imagecreatetruecolor($width, $height);
  21. $color = imagecolorallocate($final_image, 255, 255, 255);
  22. imagefill($final_image, 0, 0, $color);
  23. $x = round(($width - $tmp_image_width) / 2);
  24. $y = round(($height - $tmp_image_height) / 2);
  25. imagecopy($final_image, $tmp_image, $x, $y, 0, 0, $tmp_image_width, $tmp_image_height);
  26. // 输出
  27. $preview_img_name = 'square_img.jpg';
  28. imagejpeg($final_image, $preview_img_name, 100);
  29. imagedestroy($orgi_image);
  30. imagedestroy($tmp_image);
  31. imagedestroy($final_image);

发表评论

表情:
评论列表 (有 0 条评论,105人围观)

还没有评论,来说两句吧...

相关阅读