转换响应从HTTP请求到PNG在一个图片框c#
本文关键字:一个 HTTP 响应 请求 PNG 转换 | 更新日期: 2023-09-27 17:55:01
我使用
向web服务器发出请求HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
并在"结果"中返回以下格式,我如何将其更改为我可以在图片框中显示的PNG ?
aPic = "�PNG'r'n'u001a'n'0'0'0'rIHDR'0'0'00'0'0'00'b'u0006'0'0'0W'u0002��'0'0'0'u001dtEXtjira-system-image-type'0avatar�'u0002'u001aa'0'0'u0010�IDATx��Y�W�Y�����>s�Lw�S3�5eL'0'u0001�EY'u0015YeM'u0002a'rdO'bd'u000f!'u0010�}S'u0016'u00196q-'u0005�'u0005'u0010'u0005�...
我使用的是。net 4.0,这是一个winforms应用程序。
提前感谢。
下载数据为字节数组,并将其转换为图像,并将其放入pictureBox:
using (var webClient = new WebClient())
{
using (var stream = webClient.OpenRead("http://1.2.3.4/image.png"))
{
pictureBox1.Image = new Bitmap(stream);
}
}
PNG是用PNG压缩格式保存的位图图像,所以你需要查看位图而不是PNG,如果你查看位图类,你会看到它有一个接受流的构造函数(见MSDN)
这是一个很好的例子
private void InitializeStreamBitmap()
{
try
{
System.Net.WebRequest request =
System.Net.WebRequest.Create(
"http://www.microsoft.com//h/en-us/r/ms_masthead_ltr.gif");
System.Net.WebResponse response = request.GetResponse();
System.IO.Stream responseStream =
response.GetResponseStream();
Bitmap bitmap2 = new Bitmap(responseStream);
PictureBox1.Image = bitmap2;
}
catch(System.Net.WebException)
{
MessageBox.Show("There was an error opening the image file."
+ "Check the URL");
}
}