PHP下载远程图片至本地
今天用到下载微信文章里的素材到服务器本地,写下以下方法,以做记录
//下载远程图片至本地
function downloadImageFromWeixin($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_NOBODY, 0); // 只取body头
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$package = curl_exec($ch);
$httpinfo = curl_getinfo($ch);
curl_close($ch);
$imageAll = array_merge(array(
'imgBody' => $package
), $httpinfo);
return saveImages($imageAll);
}
// 保存图像
function saveImages($imageAll,$file="",$path="Upload/wechat/images/"){
path_exists($path); //保存地址目录查询,该方法在上篇文章有写https://www.cnblogs.com/lhm166/articles/14543486.html
$file = $file?:uniqid().rand(1000,9999);
if ($imageAll['content_type'] == 'image/gif') {
file_put_contents($path.$file.'.gif', $imageAll["imgBody"]);
return '/'.$path.$file.'.gif';
}elseif($imageAll['content_type'] == 'image/png'){
file_put_contents($path.$file.'.png', $imageAll["imgBody"]);
return '/'.$path.$file.'.png';
} elseif ($imageAll['content_type'] == 'image/webp') {
file_put_contents($path.$file.'.webp', $imageAll["imgBody"]);
$im = imagecreatefromwebp($path.$file.'.webp');
imagejpeg($im, $path.$file.'.jpg', 100);
imagedestroy($im);
return '/'.$path.$file.'.jpg';
}elseif ($imageAll['content_type'] == 'image/jpeg') {
file_put_contents($path.$file.'.jpeg', $imageAll["imgBody"]);
return '/'.$path.$file.'.jpeg';
}elseif ($imageAll['content_type'] == 'image/jpg') {
file_put_contents($path.$file.'.jpeg', $imageAll["imgBody"]);
return $path.$file.'.jpg';
}
}

浙公网安备 33010602011771号