当前位置:Gxlcms > PHP教程 > php缩略图填充白边的示例代码

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

时间:2021-07-01 10:21:17 帮助过:18人阅读

  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);

人气教程排行