ITPub博客

首页 > Linux操作系统 > Linux操作系统 > php 图像裁剪(自定义裁剪图片大小)

php 图像裁剪(自定义裁剪图片大小)

Linux操作系统 作者:yaoguocai 时间:2017-09-06 14:43:27 0 删除 编辑

点击(此处)折叠或打开

  1. <?php
  2. /**
  3. * 图像裁剪
  4. * @param $title string 原图路径
  5. * @param $content string 需要裁剪的宽
  6. * @param $encode string 需要裁剪的高
  7. */
  8. function imagecropper($source_path, $target_width, $target_height)
  9. {
  10. $source_info = getimagesize($source_path);
  11. $source_width = $source_info[0];
  12. $source_height = $source_info[1];
  13. $source_mime = $source_info['mime'];
  14. $source_ratio = $source_height / $source_width;
  15. $target_ratio = $target_height / $target_width;

  16. // 源图过高
  17. if ($source_ratio > $target_ratio)
  18. {
  19. $cropped_width = $source_width;
  20. $cropped_height = $source_width * $target_ratio;
  21. $source_x = 0;
  22. $source_y = ($source_height - $cropped_height) / 2;
  23. }
  24. // 源图过宽
  25. elseif ($source_ratio < $target_ratio)
  26. {
  27. $cropped_width = $source_height / $target_ratio;
  28. $cropped_height = $source_height;
  29. $source_x = ($source_width - $cropped_width) / 2;
  30. $source_y = 0;
  31. }
  32. // 源图适中
  33. else
  34. {
  35. $cropped_width = $source_width;
  36. $cropped_height = $source_height;
  37. $source_x = 0;
  38. $source_y = 0;
  39. }

  40. switch ($source_mime)
  41. {
  42. case 'image/gif':
  43. $source_image = imagecreatefromgif($source_path);
  44. break;

  45. case 'image/jpeg':
  46. $source_image = imagecreatefromjpeg($source_path);
  47. break;

  48. case 'image/png':
  49. $source_image = imagecreatefrompng($source_path);
  50. break;

  51. default:
  52. return false;
  53. break;
  54. }

  55. $target_image = imagecreatetruecolor($target_width, $target_height);
  56. $cropped_image = imagecreatetruecolor($cropped_width, $cropped_height);

  57. // 裁剪
  58. imagecopy($cropped_image, $source_image, 0, 0, $source_x, $source_y, $cropped_width, $cropped_height);
  59. // 缩放
  60. imagecopyresampled($target_image, $cropped_image, 0, 0, 0, 0, $target_width, $target_height, $cropped_width, $cropped_height);

  61. //保存图片到本地(两者选一)
  62. //$randNumber = mt_rand(00000, 99999). mt_rand(000, 999);
  63. //$fileName = substr(md5($randNumber), 8, 16) .".png";
  64. //imagepng($target_image,'./'.$fileName);
  65. //imagedestroy($target_image);

  66. //直接在浏览器输出图片(两者选一)
  67. header('Content-Type: image/jpeg');
  68. imagepng($target_image);
  69. imagedestroy($target_image);
  70. imagejpeg($target_image);
  71. imagedestroy($source_image);
  72. imagedestroy($target_image);
  73. imagedestroy($cropped_image);
  74. }

  75. //调用
  76. //imagecropper('./img033.jpg',300,300);
  77. imagecropper('./img033.jpg',140,140);

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29679106/viewspace-2144576/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: 没有了~
请登录后发表评论 登录
全部评论

注册时间:2014-05-27

  • 博文量
    19
  • 访问量
    13708