ThinkPHP5.0图片上传生成缩略图实例代码

很多朋友遇到这样一个问题,图片上传生成缩略图,很多人在本机(win)测试成功,上传到linux 服务器后错误。

我也遇到同样的问题。网上一查,有无数的人说是服务器临时文件目录权限问题。

几经思考后,发现并非如此。

其根本的原因是,保存到变量的信息是之前的,之后又move移动到了自己指定的目录下,同时临时文件已经不存在。所以再生成缩略图的时候,需要open的,文件地址应该是自己定义的目录+文件名。然而很多实例文档中,还是使用的move 之前的信息。

又加之在win服务器下,move后,指定目录已生成了文件,同时临时文件未被删除。所以能用move之前的信息生成缩略图。

希望不多的言语能帮助遇到同样问题的你。

下面在通过实例代码给大家介绍ThinkPHP5.0图片上传生成缩略图的方法。

代码如下所示:

 1 <?php
 2 namespace app\common\controller;
 3 use app\common\model\Goods;
 4 class Tools
 5 {
 6  public static function upload_goods_img($whereName="", $width="", $height="")
 7  {
 8  // 打开图片的相对路径
 9  $imgpath = config('img_path');
10  // 绝对路径
11  $imgRootPath = config('imgRootPath');
12  $storeId = '自定义';
13  $merchantId = '自定义';
14  $old_filename = $storeId . $merchantId . time();
15  $filename = $storeId . $merchantId . time() . mt_rand(1000, 9999);
16  $type = Goods::upload($whereName, $old_filename);
17  if($type)
18  {
19   $savepath = $imgRootPath . '/' . $whereName . '/' . $filename . '.' . $type;
20   $thumbfile = $filename . '.' . $type;
21   $thumbName = $imgpath . '/' . $whereName . '/' . $thumbfile;
22   $image = \think\Image::open($imgpath . '/'. $whereName .'/' . $old_filename . '.' . $type);
23   $image->thumb($width, $height, \think\Image::THUMB_FIXED)->save($thumbName);
24   $data = [
25   'access_url' => $imgRootPath . '/' . $whereName . '/' . $filename . '.' . $type,
26   'filename' => $thumbfile,
27   ];
28   return $data;
29  }
30  }
31 }

调用:

 1 class Goods
 2 {
 3  public function upload_sku()
 4  {
 5  $whereName = 'goods/sku';
 6  $width = 750;
 7  $height = 750;
 8  $data = Tools::upload_goods_img($whereName,$width, $height);
 9  return returnJson(1, '上传成功', $data);;
10  }
11 }

猜你喜欢

转载自www.cnblogs.com/gedage/p/10009621.html