Channels ▼
RSS

.NET

Dynamic Images and Databases


A Web site is made of two types of images-helper images used to embellish the layout and substantial images that add content and information to the site. Helper images are small, immutable and can be successfully cached on the browser and reused. Depending on the application, a substantial image may be subject to dynamic changes and variations. As an example, you can think of the image that represents the daily diagram of a stock exchange index. In this case, you employ ad hoc techniques to generate the image on the fly and serve it to the user through a lean and mean HTTP handler. A made-to-measure HTTP handler is far better than an ad hoc Web page because of the simplified lifecycle it produces. What if you also need to store a dynamically generated image for reloading it later? Should you opt for a database or is the file system still the most effective solution?

The use of the database as the storage medium for images has always been a controversial topic. Some people have good reasons to push it as a solution whereas others have as good reasons to tell you the exact opposite. Fact is, all DBMS systems of a certain reputation have supported BLOB objects for quite some time. And there must be a reason for this. Often used to contain an image, a BLOB field, though, is designed to contain a binary object including multimedia contents or long text.

To read an image from a BLOB field with ADO.NET, you execute a SELECT statement on the column and use the ExecuteScalar method to save the result in an array of bytes. Next, you send this array down to the client through a binary write to the response stream. Here's an example:


SqlConnection conn = new SqlConnection(connString);
using (conn) {
   SqlCommand cmd = new SqlCommand(cmdText, conn);
   cmd.Parameters.AddWithValue("@id", id);
   conn.Open();
   img = (byte[]) cmd.ExecuteScalar();
   conn.Close();
}

if (img != null) {
   Response.ContentType = "image/jpeg";
   Response.BinaryWrite(img);
}

To store an image in a database field, you use an INSERT or UPDATE statement and pass the BLOB field an array of bytes. Here's how:


SqlConnection conn = new SqlConnection(connString);
using (conn)
{
   string cmdText = "INSERT INTO MyPics (bits) " +
                    "VALUES (@imageBits)";
   SqlCommand cmd = new SqlCommand(cmdText, conn);

   cmd.Parameters.AddWithValue("@imageBits", img, size); 
   conn.Open();
   cmd.ExecuteNonQuery();
   conn.Close();
}

If you're using the FileUpload control to upload an image (i.e., the picture of a user), you get the bits as follows from the PostedFile.InputStream property on the FileUpload control.

Note also that most DBMS apps (for example, Oracle and SQL Server) also provide ad hoc statements to manage large binary objects. In spite of the availability of specialized tools, though, be aware that manipulating large chunks of binary data is anyway problematic for a database.

In the end, should you really consider storing images in a database? If you need to frequently edit the images, I suggest you store the images as separate files. If the size of the images are very large (say, hundreds of megabytes), I still suggest you store the images as separate files. If your images are essentially read-only and relatively static, and if you measure the size in KB, then using a database is generally fine.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video