C#中http返回的图片数据流如何转成图片存到本地

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#中http返回的图片数据流如何转成图片存到本地相关的知识,希望对你有一定的参考价值。

ASP。NET中我给服务器发了一个HTTP请求,返回一张图片,现在我想在后台完成这张图片的保存过程。

参考技术A 给你一个下载图片的类,自己参考一下。

using System;
using System.Net;
using System.IO;
using System.Text;

namespace mynamespace

public class Downloader

/// <summary>
/// 下载图片
/// </summary>
/// <param name="picUrl">图片Http地址</param>
/// <param name="savePath">保存路径</param>
/// <param name="timeOut">Request最大请求时间,如果为-1则无限制</param>
/// <returns></returns>
public static bool DownloadPicture(string picUrl, string savePath,int timeOut)

bool value = false;
WebResponse response = null;
Stream stream = null;
try

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(picUrl);
if (timeOut != -1) request.Timeout = timeOut;
response = request.GetResponse();
stream = response.GetResponseStream();
if (!response.ContentType.ToLower().StartsWith("text/"))
value = SaveBinaryFile(response, savePath);

finally

if(stream!=null) stream.Close();
if (response != null) response.Close();

return value;

private static bool SaveBinaryFile(WebResponse response, string savePath)

bool value = false;
byte[] buffer = new byte[1024];
Stream outStream = null;
Stream inStream = null;
try

if (File.Exists(savePath)) File.Delete(savePath);
outStream = System.IO.File.Create(savePath);
inStream = response.GetResponseStream();
int l;
do

l = inStream.Read(buffer, 0, buffer.Length);
if (l > 0) outStream.Write(buffer, 0, l);
while (l > 0);
value = true;

finally

if(outStream!=null) outStream.Close();
if(inStream!=null) inStream.Close();

return value;


参考技术B System.Drawing.Image.FromStream()创建一个Image实例,
再调用Image实例的Save方法就可以保存到文件。

PHP远程下载图片,微信头像存到本地,本地图片转base64

方法一(推荐):

function download_remote_pic($url){
    $header = [
        ‘User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0‘,      
        ‘Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3‘,      
        ‘Accept-Encoding: gzip, deflate‘,
    ];  
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_ENCODING, ‘gzip‘);  
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    $data = curl_exec($curl);
    $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);  
    if ($code == 200) {//把URL格式的图片转成base64_encode格式的!      
       $imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);  
    }  
    $img_content=$imgBase64Code;//图片内容  
    //echo $img_content;exit;  
    if (preg_match(‘/^(data:s*image/(w+);base64,)/‘, $img_content, $result)) {   
        $type = $result[2];//得到图片类型png?jpg?gif?   
        $new_file = "./".time().rand(1,10000).".{$type}";   
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], ‘‘, $img_content)))) {  
            return $new_file; 
        }
    } 
}
$new_file = download_remote_pic(‘http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLlib3rTHIt2n0nrYFibmOc69IWwLABiaEMicfg0iahGUhP93jYicNZ5MWL9yYlHvibdlG36xWHuPs0p3ibPQ/132‘);

echo $new_file;

方法二(慢,消耗服务器)

$url=‘http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLlib3rTHIt2n0nrYFibmOc69IWwLABiaEMicfg0iahGUhP93jYicNZ5MWL9yYlHvibdlG36xWHuPs0p3ibPQ/132‘;  
$new_file = "./".time().rand(1,10000).".png"; //图片类型getimagesize($url)可以但是因为是远程图片太慢了
file_put_contents($new_file, file_get_contents($url));
echo ($new_file);

图片转base64

function base64_encode_image($file){
    $type=getimagesize($file);//取得图片的大小,类型等  
    $fp=fopen($file,"r")or die("Can‘t open file");  

    $file_content=chunk_split(base64_encode(fread($fp,filesize($file))));//base64编码  
    switch($type[2]){//判读图片类型  
        case 1:$img_type="gif";break;  
        case 2:$img_type="jpg";break;  
        case 3:$img_type="png";break;  
    }  
    $img=‘data:image/‘.$img_type.‘;base64,‘.$file_content;//合成图片的base64编码  
    fclose($fp);  
    return $img;
}

 

以上是关于C#中http返回的图片数据流如何转成图片存到本地的主要内容,如果未能解决你的问题,请参考以下文章

C# 如何把图片放到sql server数据库中

在ASP.NET中怎么把图片上传,并且存入数据库,求大神解答!!!!

在java中如何把字节数组存储到数据库?

蓝懿IOS图片编辑模块

c# 保存图片文件 winform

如何将图片存到数据库