如何下载&使用asp.net
显示来自URL的图像e.g。我有一个页面ShowImage.aspx 当我调用此页面时,它应该显示来自外部URL的图像(来自Response Stream) https://appharbor.com/assets/images/stackoverflow-logo.png
使用Response.ContentType =“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();
}
答案 0 :(得分:6)
您只需使用Image control
的Image.ImageUrl属性即可<asp:Image id="img1" runat="server" ImageUrl="https://appharbor.com/assets/images/stackoverflow-logo.png" />
如果要从服务器端设置Image 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);
}
答案 1 :(得分: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;
}
}
}
}
}