1

如何使用 asp.net 从 URL 下载和显示图像

例如,我有一个页面 ShowImage.aspx 当我调用此页面时,它应该显示来自外部 URL https://appharbor.com/assets/images/stackoverflow-logo.png的图像(来自响应流)

带有 Response.ContentType = "图像/png"

自行解决

    protected void Page_Load(object sender, EventArgs e)
    {
        WebRequest req = WebRequest.Create("https://appharbor.com/assets/images/stackoverflow-logo.png");
        WebResponse response = req.GetResponse();
        Stream stream = response.GetResponseStream();

        Byte[] buffer = null;
        Response.Clear();
        Response.ContentType = "image/png";
        Response.AddHeader("Content-Length", response.ContentLength.ToString());

        int bytesRead = 0;
        do
        {
            buffer = new Byte[4096];
            bytesRead = stream.Read(buffer, 0, buffer.Length);

            if (bytesRead > 0)
            {
                Response.OutputStream.Write(buffer,0,bytesRead);
            }
        } while (bytesRead > 0);
        Response.End();
    }

参考:http ://forums.asp.net/t/1401931.aspx/1

4

2 回答 2

6

您可以简单地使用 Image 控件的Image.ImageUrl属性

<asp:Image id="img1" runat="server" ImageUrl="https://appharbor.com/assets/images/stackoverflow-logo.png" />

如果你想从服务器端设置图片网址(代码后面)

img1.ImageUrl = "http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.image.imageurl.aspx";

如果您使用 WebRequest 从 url 获取图像字符串。

WebRequest req = WebRequest.Create("https://appharbor.com/assets/images/stackoverflow-logo.png");
WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();
System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
using (MemoryStream ms = new MemoryStream())
{
     image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
     ms.WriteTo(Response.OutputStream);
}
于 2013-04-29T09:38:21.517 回答
0
 public class Service1 : IService1
    {
        public Stream GetImage()
        {
            WebOperationContext.Current.OutgoingResponse.ContentType = "image/jpeg";
            using(WebClient Client = new WebClient())
            {
               using(StreamReader Reader = new StreamReader(Client.OpenRead("FILE URL")))
               {
                 try
                 {
                   string Contents = Reader.ReadToEnd();
                   Reader.Close();
                   return Contents;
                 }
                 catch
                 {
                    return string.Empty;
                 }
               }
            }
        }
    }
于 2013-04-29T09:52:48.410 回答