欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php缩略图填充白边的示例代码

程序员文章站 2022-04-05 16:38:52
...
  1. //源图的路径,可以是本地文件,也可以是远程图片

  2. $src_path = '1.jpg';
  3. //最终保存图片的宽
  4. $width = 160;
  5. //最终保存图片的高
  6. $height = 120;
  7. //源图对象

  8. $src_image = imagecreatefromstring(file_get_contents($src_path));
  9. $src_width = imagesx($src_image);
  10. $src_height = imagesy($src_image);
  11. //生成等比例的缩略图

  12. $tmp_image_width = 0;
  13. $tmp_image_height = 0;
  14. if ($src_width / $src_height >= $width / $height) {
  15. $tmp_image_width = $width;
  16. $tmp_image_height = round($tmp_image_width * $src_height / $src_width);
  17. } else {
  18. $tmp_image_height = $height;
  19. $tmp_image_width = round($tmp_image_height * $src_width / $src_height);
  20. }
  21. $tmpImage = imagecreatetruecolor($tmp_image_width, $tmp_image_height);

  22. imagecopyresampled($tmpImage, $src_image, 0, 0, 0, 0, $tmp_image_width, $tmp_image_height, $src_width, $src_height);
  23. //添加白边

  24. $final_image = imagecreatetruecolor($width, $height);
  25. $color = imagecolorallocate($final_image, 255, 255, 255);
  26. imagefill($final_image, 0, 0, $color);
  27. $x = round(($width - $tmp_image_width) / 2);

  28. $y = round(($height - $tmp_image_height) / 2);
  29. imagecopy($final_image, $tmpImage, $x, $y, 0, 0, $tmp_image_width, $tmp_image_height);

  30. //输出图片

  31. header('Content-Type: image/jpeg');
  32. imagejpeg($final_image);
复制代码