Jagd
Jagd

Reputation: 7306

How to display images in MemoryStream?

I have some images (png's and jpg's mostly) that I'm storing in SQL Server 2008's FileStream. I am able to retrieve said images and store them in a MemoryStream.

I have a certain webpage that I need to display the image on that is within the MemoryStream. Is there some way that I can go about displaying the contents of the MemoryStream within an HTML image tag (or even better, within an ASP.NET Image control)?

Upvotes: 1

Views: 13968

Answers (2)

Ravi Ram
Ravi Ram

Reputation: 24488

I am using the following code to get image from a remote URL into - MemoryStream - System.Drawing.Image

// Set image url
string imgURL = ("http://cdn.flikr.com/images/products/" + imageName);

// Get image into memory
WebClient lWebClient = new WebClient();
byte[] lImageBytes = lWebClient.DownloadData(imgURL);
MemoryStream imgStream = new MemoryStream(lImageBytes);

image = System.Drawing.Image.FromStream(imgStream);

if (image.Width >= 200)
{
    // do something
}

Upvotes: 2

Jason Meckley
Jason Meckley

Reputation: 7591

yes,

  1. point the image source to a ashx handler
  2. have the handler query the image from the database
  3. write the bytes to the response stream and set the content type

html

<img src="loadimage.ashx?id=..."/>

add a generic handler to your project and loadimage handler

class loadimage: ihttphandler
{
   public void Process(HttpContext context)
   {

        var id = context.Request["id"];
        var row = GetImageFromDb(id);

        var response = context.Response;
        response.AddHeader("content-disposition", "attachment; filename=" + row["anem of image"]);
        response.ContentType = row["mime type"].ToString(); //png or gif etc.
        response.BinaryWrite((byte[])row["image blob"]);
   }

   public bool Reuse { get {return true; } }
}

Upvotes: 10

Related Questions