微信公眾平台開發(77) 圖片下載


微信公眾平台的用戶頭像和接口取到的用戶上傳圖片都做了防盜處理,不能被其他網頁引用。

例如,下面是在引用用戶頭像的圖片的時候,提示未經允許不可引用。

 

本文介紹如何下載這些圖片的方法!

一、下載圖片所有信息

使用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);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM