微信公众平台的用户头像和接口取到的用户上传图片都做了防盗处理,不能被其他网页引用。
例如,下面是在引用用户头像的图片的时候,提示未经允许不可引用。

本文介绍如何下载这些图片的方法!
一、下载图片所有信息
使用CURL的方式下载
function downloadImageFromQzone($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 $imageAll;
}
返回将返回图片的二进制数据及http头信息
http头如下
["url"]=> string(66)"http://mmsns.qpic.cn/mmsns/L4qjYtOibumlqutvkb6r0V0KCjEJM76NFiawL5tDicOZn9ibKgIaiaUfeRA/0" ["content_type"]=> string(10)"image/jpeg" ["http_code"]=> int(200) ["header_size"]=> int(374) ["request_size"]=> int(258) ["filetime"]=> int(-1) ["ssl_verify_result"]=> int(0) ["redirect_count"]=> int(0) ["total_time"]=> float(0.289523) ["namelookup_time"]=> float(0.002558) ["connect_time"]=> float(0.003475) ["pretransfer_time"]=> float(0.003477) ["size_upload"]=> float(0) ["size_download"]=> float(42240) ["speed_download"]=> float(145895) ["speed_upload"]=> float(0) ["download_content_length"]=> float(42240) ["upload_content_length"]=> float(0) ["starttransfer_time"]=> float(0.241982) ["redirect_time"]=> float(0)
二、根据http头做一些过滤
一些明显不符合要求的图片就直接忽略掉,没有必要保存
$imageExt = (0 < preg_match('{image/(w+)}i', $imageAll["content_type"], $extmatches))? $extmatches[1]: "jpeg";
if (preg_match('{(jpg|jpeg|png)$}i', $imageExt) == 0){ //非jpg,jpeg,png格式
$contentStr = "不支持类型";
}else if ($imageAll["download_content_length"]/1024 > 200){ //大于200K
$contentStr = "图片太大";
}else if ($imageAll["total_time"] > 1){ //大于1秒
$contentStr = "网速太慢";
}
三、保存图片二进制数据
保存到BAE
$fileUpload = $imageAll["imgBody"];
require_once (dirname( __FILE__ ). '/bcs/bcs.class.php');
$host = 'bcs.duapp.com';
$ak = '';
$sk = '';
$bucket = '';
$filename = time ();
$object = '/images/'.$filename.'.jpg';
$baiduBCS = new BaiduBCS ( $ak, $sk, $host );
$opt = array("acl" => "public-read");
$response = $baiduBCS->create_object_by_content( $bucket, $object, $fileUpload, $opt );
保存到SAE
if (isset($_SERVER['HTTP_APPNAME'])){
//SAE环境
$s = new SaeStorage();
$s->write($domain, $filename, $imageAll["imgBody"]);
}
保存到本地
//本地操作
$local_file = fopen($filename, 'w');
if (false !== $local_file){
if (false !== fwrite($local_file, $imageAll["imgBody"])) {
fclose($local_file);
}
}




