从后台的URL下载并显示图像

本文关键字:显示 显示图 图像 下载 后台 URL | 更新日期: 2023-09-27 18:11:13

如何下载&使用asp.net

显示来自URL的图像

。我有一个页面showimage。aspx当我调用这个页面,它应该显示图像(从响应流)从外部URLhttps://appharbor.com/assets/images/stackoverflow-logo.png

与反应。内容类型= "Image/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

从后台的URL下载并显示图像

您可以简单地使用图像。图像控件的ImageUrl属性

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

如果你想从服务器端设置图像url(后面的代码)

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);
}
 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;
                 }
               }
            }
        }
    }