php下载远程图片并且生成缩略图
发表于:2024-04-19 10:57:31浏览:233次
引言
缩略图调用的是thinkphp5.0的组件
composer require topthink/think-image --no-plugins
需要引入文件类:https://blog.dazijie.com/article/104
代码
use app\common\utils\File;
public function downloadImg($fileurl,$thumb_max_width = 150,$thumb_max_height = 150)
{
$date = date('Ymd');
$imginfo = getimagesize($fileurl);
$mime = $imginfo['mime'];
$exts = [
'image/jpeg'=>'jpg',
'image/png'=>'png',
'image/gif'=>'gif',
'image/svg+xml'=>'svg'
];
$ext = $exts[$mime];
// getcwd() 输出=>/www/wwwroot/xxxx.xxxx.com/public
$str = md5(uniqid(md5(microtime(true)),true));
$str = md5(sha1($str));
$sub1 = '/spider/images/'.$date;
$sub2 = '/'.$str.'.'.$ext;
$img_path = $sub1.$sub2;
$img_thumb = $sub1.'/thumb'.$sub2;
$content = file_get_contents($fileurl);
if (!$content) {
return false;
}
File::write(getcwd().$img_path,$content);
File::autoCreateDir(getcwd().$img_thumb);
$image = \think\Image::open(getcwd().$img_path);
// 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.png
$image->thumb($thumb_max_width, $thumb_max_height)->save(getcwd().$img_thumb);
return compact('img_path','img_thumb');
}
栏目分类全部>