从URL下载和显示图像

时间:2013-09-11 19:25:55

标签: asp.net vb.net

我试图创建一个可以下载并返回图像的代理图像加载器。我的代码非常接近,它显示的是一个图像,但我相信有些字节不是正确的:

Dim myRequest As WebRequest = WebRequest.Create(URL)
Dim myResponse As WebResponse = myRequest.GetResponse()
Response.ContentType = "image/jpeg"
Response.Clear()
Response.BufferOutput = True
Dim strm As Stream = myResponse.GetResponseStream()
Dim buffer As Byte() = New Byte(4095) {}
Dim byteSeq As Integer = strm.Read(buffer, 0, 4096)
Do While byteSeq > 0
    Response.OutputStream.Write(buffer, 0, 4096)
    byteSeq = strm.Read(buffer, 0, 4096)
    Response.Flush()
Loop

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

试试这个:

Dim theRequest As WebRequest = WebRequest.Create(URL)
Dim theResponse As WebResponse = theRequest.GetResponse()
Dim theStream As Stream = theResponse.GetResponseStream()
Dim theImage As System.Drawing.Image = System.Drawing.Image.FromStream(theStream)

Using theMemoryStream As New MemoryStream()
    theImage.Save(theMemoryStream, System.Drawing.Imaging.ImageFormat.Jpeg)
    theMemoryStream.WriteTo(Response.OutputStream)
End Using

注意:您也可以将ASP.NET Image服务器控件指向要下载的图像的URL,如下所示:

<asp:Image id="img1" runat="server" ImageUrl="URL" />