ThinkPHP5.0 怎么实现图片上传生成缩略图?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
代码如下所示:
<?php
namespace app\common\controller;
use app\common\model\Goods;
class Tools
{
public static function upload_goods_img($whereName="", $width="", $height="")
{
// 打开图片的相对路径
$imgpath = config('img_path');
// 绝对路径
$imgRootPath = config('imgRootPath');
$storeId = '自定义';
$merchantId = '自定义';
$old_filename = $storeId . $merchantId . time();
$filename = $storeId . $merchantId . time() . mt_rand(1000, 9999);
$type = Goods::upload($whereName, $old_filename);
if($type)
{
$savepath = $imgRootPath . '/' . $whereName . '/' . $filename . '.' . $type;
$thumbfile = $filename . '.' . $type;
$thumbName = $imgpath . '/' . $whereName . '/' . $thumbfile;
$image = \think\Image::open($imgpath . '/'. $whereName .'/' . $old_filename . '.' . $type);
$image->thumb($width, $height, \think\Image::THUMB_FIXED)->save($thumbName);
$data = [
'access_url' => $imgRootPath . '/' . $whereName . '/' . $filename . '.' . $type,
'filename' => $thumbfile,
];
return $data;
}
}
}
调用:
class Goods
{
public function upload_sku()
{
$whereName = 'goods/sku';
$width = 750;
$height = 750;
$data = Tools::upload_goods_img($whereName,$width, $height);
return returnJson(1, '上传成功', $data);;
}
}
PS:下面在看一段代码tp5中上传图片方法,并生成相应缩略图的方法
//接收上传文件的name
$file = $this->_req->file("upload_head_image");
//将上传的文件移动到public/uploads/user
$info = $file->validate(['size'=>5242880,'ext'=>'jpg,jpeg,png'])->move(ROOT_PATH . 'public' . DS . 'uploads' . DS . 'user');
if($info){
$pic = new \app\home\model\User();
$pic_url = $pic->thumbImage($file,$info);
$user['portrait'] = 'uploads/user/'.$pic_url;
//print_r($pic_url);exit();
}
///model中代码如下
/**
* [生成用户头像缩略图,180、50]
* @param [type] $file [获取上传文件$_FILE]
* @param [type] $pic [上传文件的路径]
* @return [type] [返回处理后的文件路径]
*/
public function thumbImage($file,$pic){
$image = \think\Image::open($file);
$getSaveName = str_replace('\\','/',$pic->getSaveName());
$portrait_thumbnail_180= 'uploads/user/'.str_replace($pic->getFilename(),'180_'.$pic->getFilename(),$getSaveName);
$image->thumb(180,180,\think\Image::THUMB_CENTER)->save(ROOT_PATH . 'public' . DS . $portrait_thumbnail_180,null,100,true);
$portrait_thumbnail_80 = 'uploads/user/'.str_replace($pic->getFilename(),'80_'.$pic->getFilename(),$getSaveName);
$image->thumb(80,80,\think\Image::THUMB_CENTER)->save(ROOT_PATH . 'public' . DS . $portrait_thumbnail_80,null,100,true);
$portrait_thumbnail_50 = 'uploads/user/'.str_replace($pic->getFilename(),'50_'.$pic->getFilename(),$getSaveName);
$image->thumb(50,50,\think\Image::THUMB_CENTER)->save(ROOT_PATH . 'public' . DS . $portrait_thumbnail_50,null,100,true);
if ($image) {
return $getSaveName;
}
}
看完上述内容,你们掌握ThinkPHP5.0 怎么实现图片上传生成缩略图的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。