0
Posted on 6:38 AM by Softminer and filed under

there are two ways to return an image in asp.net as response , I tested both and the first 1 is much faster.

the first one is to use the Stream:


            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://www.yourwebsite.com/image.jpg");
            request.Timeout = 5000;
            request.ReadWriteTimeout = 20000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            System.Drawing.Image img = System.Drawing.Image.FromStream(response.GetResponseStream());
            img.Save(Response.OutputStream, ImageFormat.Jpeg);
            img.Dispose();

the second one is to use binary:

        WebRequest request = WebRequest.Create("http://www.yoursite.com/image.jpg");
        request.Credentials = CredentialCache.DefaultCredentials;
        HttpWebResponse   resp = (HttpWebResponse)request.GetResponse();
        Stream dataStream = resp.GetResponseStream();
        Response.Clear();
        Response.ContentType = resp.ContentType;
        BinaryReader reader = new BinaryReader(dataStream);
        Response.BinaryWrite(reader.ReadBytes(Convert.ToInt32( resp.ContentLength)));
        Response.Flush();
        reader.Close();
        dataStream.Close();
        resp.Close();

and you can access the both by using
<img src="http://localhost/WebSite/yourpage.aspx" />

PS: you can also write a handler which return back the image as output Response:

<%@ WebHandler Language="C#" Class="Handler" %>


using System;
using System.Web;
public class Handler : IHttpHandler {
    public void ProcessRequest(HttpContext context)
    {
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(path);
            request.Timeout = 5000;
            request.ReadWriteTimeout = 20000;
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            System.Drawing.Image img = System.Drawing.Image.FromStream(response.GetResponseStream());
            img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            img.Dispose();
    }
    public bool IsReusable {
        get {
            return true;
        }
    }
}
0
Responses to ... Image handler for ASP.NET