Sunday, November 11, 2007

CodeGuru: Load Images from and Save Images to a Database

CodeGuru: Load Images from and Save Images to a Database

Environment: .NET, VB
Introduction
Sometimes you need to store images in a database instead of as physical files. This sample application will show you how to build a Windows Forms interface that allows you to do the following:
Browse for an image on your hard disk
Load the selected image into a PictureBox control for viewing
Save an image displayed in the PictureBox control to the database
Select an image from a ListBox control, and load it from the database
New Concepts

the Image data type with the word image, as if to imply that only images can be stored therein. Rather, the Image data type can store anything as variable-length binary data.
A byte array is used to send data to an Image field. Thus, the main question is: How does one convert an image file—whether a JPEG, Bitmap, or other format—into an array of bytes? There are several ways to accomplish this in .NET. One of the easiest ways is to use a concrete implementation of the Stream class. A stream in .NET is essentially an abstraction of a sequence of bytes, whether these bytes came from a file, a TCP/IP socket, a database, or wherever. Stream classes allow you to work with binary data, reading and writing back and forth between streams and data structures (such as a byte array).
Once the image is converted to a byte array, it's saved to a database by using coding.