feronovak
feronovak

Reputation: 2697

How to read picture from URL and show it on my page

I have a sql table which holds information:

   id (hash)
   imagename string
   width int
   height int

What is the best way to create .net image read which will show images in page. I would like to call it like image.aspx/ashx?id=[id] and function will try to catch and show that image.

I know how to get data from SQL but I dont know how to read img from URL and show it as image.

Could any please point me at some relevant information how to do it or show piece of code how it works?

Do I read it as stream?

Thanks

Upvotes: 0

Views: 3175

Answers (3)

Chris Shouts
Chris Shouts

Reputation: 5427

You can retrieve remote resources (such as images) via HTTP using the System.Net.WebRequest class.

WebRequest request = WebRequest.Create("http://www.doesnotexist.com/ghost.png");
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
BinaryReader reader = new BinaryReader(stream)
byte[] imageBytes = reader.ReadBytes(stream.Length);

Note that there might be better ways to read the bytes from the Stream. You should also remember to add using statements where appropriate to properly dispose of any unmanaged resources.

Upvotes: 0

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35126

string imageFileName = "thefile.jpg";
context.Request.MapPath(@"IMAGES\" + context.Request.QueryString["id"]); 
context.Response.ContentType = "image/jpeg";     
context.Response.WriteFile(imageFileName);     
context.Response.Flush(); 
context.Response.Close();

http://blogs.msdn.com/b/alikl/archive/2008/05/02/asp-net-performance-sin-serving-images-dynamically-or-another-reason-to-love-fiddler.aspx

http://msdn.microsoft.com/en-us/library/ms973917.aspx

Upvotes: 1

Mike Cole
Mike Cole

Reputation: 14703

Check out this article: http://aspnet-cookbook.info/O.Reilly-ASP.NET.Cookbook.Second.Edition/0596100647/aspnetckbk2-CHP-20-SECT-2.html

You'll want to create an HttpHandler class and wire that up in your web.config.

Upvotes: 1

Related Questions