原创

tp6生成缩略图传参-按照要求生成合适大小的缩略图


在实际生产过程中,我们经常会遇到上传的图片于实际使用中图片比例不同的情况,对于很多老旧数据,我们也不可能重新去将所有的图片再传一遍,于是在图片的img标签中,如果能够按照我们的参数重新生成合适大小的缩略图,那么再好不过了。
于是我本着方便大家的原则,将我的项目按照以上的思路整理了一番,下面是我的源代码~[如果大家有更好的思路,欢迎指正点评~]
本文开启了评论权限

下面是源代码:

本源代码仅仅适合于tp5,tp5.1,tp6.0等,使用前请自行安装tp的图片处理类

  1. /**
  2. * 根据传来的函数 生成合适的缩略图
  3. * @param $path
  4. * @param int $width
  5. * @param int $height
  6. * $type 1裁剪 ,2缩略
  7. * @return string
  8. */
  9. function img_thumber($path,$width=150,$height=115,$type=1){
  10. //return "/application/myclass/phpthumber/phpThumb.php?src={$path}&w={$width}&h={$height}";
  11. $old_path = $path;
  12. //去除域名
  13. if (strstr($path,"http")){
  14. $domain = request()->domain();
  15. $start = strlen($domain);
  16. $end = strlen($path);
  17. $path = substr($path,$start,$end);
  18. }
  19. //判断原图路径 是否为图片 没有则新生成
  20. /*if(is_file(".".$path)){
  21. return $path;
  22. }*/
  23. //组个新图片的路径及名称
  24. $arr = explode("/",$path);
  25. $name = md5(end($arr));
  26. array_pop($arr);
  27. $arr[] = $name;
  28. if(!$arr[0]){
  29. unset($arr[0]);
  30. }
  31. $str = '';
  32. foreach ( $arr as $k => $v){
  33. $str .= "/".$v;
  34. }
  35. $suoluetu1_name = $str."_".$width."_".$height.".png";
  36. if(is_file('.'.$suoluetu1_name)){
  37. return $suoluetu1_name;
  38. }
  39. //$image->crop(300, 300)->save('./crop.png');
  40. try{
  41. $image = \think\Image::open('.'.$path);
  42. $suoluetu1_name = ".".$suoluetu1_name;
  43. if($type == 2){
  44. $image->thumb($width, $height)->save($suoluetu1_name); //缩略
  45. }
  46. if($type == 1){
  47. //居中裁剪
  48. $image->thumb($width, $height,\think\Image::THUMB_CENTER)->save($suoluetu1_name);
  49. }
  50. //$image->crop(300, 300)->save('./crop.png');
  51. $suoluetu1_name = substr($suoluetu1_name,1,strlen($suoluetu1_name));
  52. }catch (Exception $exception){
  53. $suoluetu1_name = $old_path;
  54. }
  55. return $suoluetu1_name;
  56. }
留言反馈
问题反馈渠道,如有软件无法下载或者其他问题可反馈。【由于某种原因,目前留言不展示】
用户需要登录后才能留言反馈