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

原创
2016-07-25 08:54:59 710浏览
  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);

复制代码


声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
上一条:php时区转换函数示例 下一条:PHP邮箱地址正确性验证示例

相关文章

查看更多