获取图片为二进制流,并且显示图片到网页

时间:2022-07-20 20:27:09

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadPage();
}
}
private void LoadPage()
{
string url = "http://app-server/wa/Plex/mossout/Preview.ashx?pid=52&id=5";
byte[] m_buffer = DownloadImage(url);
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(m_buffer);
}
#region 获取图片的二进制流
/// <summary>
/// 获取图片的二进制流
/// </summary>
/// <returns></returns>
public static byte[] DownloadImage(string url)
{

HttpWebRequest rqs = HttpWebRequest.Create(url)
as HttpWebRequest;
rqs.Credentials = CredentialCache.DefaultCredentials;
rqs.Credentials = CredentialCache.DefaultNetworkCredentials;
rqs.Accept = "*/*";
rqs.KeepAlive = true;
rqs.Method = "GET";
rqs.ContentType = "application/x-www-form-urlencoded";
rqs.CookieContainer = null;
rqs.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; InfoPath.3)";
rqs.Timeout = 50000;
System.Net.ServicePointManager.ServerCertificateValidationCallback += (se, cert, chain, sslerror) =>
{ return true; };
HttpWebResponse hwResponse = rqs.GetResponse() as HttpWebResponse;
byte[] m_buffer = new byte[1024 * 1024];
Stream stream = hwResponse.GetResponseStream();
int offset = 0;
int count = 0;
do
{
count = stream.Read(m_buffer, offset, m_buffer.Length - offset);
if (count > 0)
{
offset += count;
}

} while (count > 0);
hwResponse.Close();
if (offset > 0)
{
byte[] ret = new byte[offset];
Array.Copy(m_buffer, ret, offset);
return ret;
}
else
{
return null;
}
}
#endregion