开发者

Read image from stream database

Dear's all, I have an issue in streaming databa开发者_开发知识库se.

I have already write an image there and now i want to recall and put it in a PictureBox.

Is there anyone how can tell me the best practice to do it?

Thank you very much in advance.


When the image is small or the traffic is insignificant, any of the methods mentioned above works and they make great demoware. Things start to get out of hand as the size of the image increases, because all these solutions require the entire image to be stored as a byte array in memory. If the load on the server is significant, having all these copies of image files taking up valuable process address space real estate adds up and can dramatically impact performance.

It is possible to read from a database with stream semantics, so that no entire copy of the file is ever stored in memory:

  • use the CommandBehavior.SequentialAccess hint:

Provides a way for the DataReader to handle rows that contain columns with large binary values. Rather than loading the entire row, SequentialAccess enables the DataReader to load data as a stream. You can then use the GetBytes or GetChars method to specify a byte location to start the read operation, and a limited buffer size for the data being returned.

  • read the data in chunks, using SqlDataReader.GetBytes
  • write the data to the output stream in chunks

The last point is a little problematic. You can either write the stream into a WWW server local folder that is virtually mapped to the site and then return an URL to this file. Or you can have an URL that reads the picture itself and writes the image straight to the ASP output cache. The first method can pay off for frequently accessed images, as the cached file can server multiple requests but it requires invalidation and cleanup logic. The second method is better for unfrequented accessed images, but requires proper routing logic in your app.

When things start getting really hot then the issue of threads being blocked in marshaling these images start showing up and you will have to move to Asynchronous pages, a model that fits stream copy semantics perfectly.


  1. Cal the ExecuteNonQuery method to get a byte array with the image
  2. Create a new MemoryStream around the byte array (do not destroy the stream as the Image object will continue to use it)
  3. Call Image.FromStream to read the stream
  4. Set this image to the Image property of a PictureBox.


The simplest way IMO is to read all the data from the database and write it into a MemoryStream. Rewind the stream (set Position=0) and then use new Bitmap(stream) or Image.FromStream. Note that you should not dispose of the stream... the bitmap effectively "owns" the stream after you've constructed it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜