Introduction
In a recent project, I had a situation with a lot of ad-hoc images, and these images were associated with certain profiles. It was decided that the images should reside in the database.
So, the task at hand was to be able to get these images out of the database and render them on the web pages dynamically.
This code snippet/control does just that. It takes the image identifier (key to the image in the database), reads the appropriate image from the DB, and then generates a dynamic, virtual image which can then be referenced on the ASP.NET page.
private void Page_Load(object sender, System.EventArgs e)
{
PicGen genPic = new PicGen();
int id = Convert.ToInt32(Request.QueryString["id"]);
genPic.OutputPicture( this, id);
}
string ConnectionString =
ConfigurationSettings.AppSettings["connectionString"];
private byte[] image ;
private void getImg(int imgId){
SqlConnection conn = new SqlConnection(ConnectionString);
SqlDataReader rdr=null ;
SqlCommand cmd=null ;
try{
image = new byte[' '];
conn.Open();
cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText =
"select imageId, imageBolb from myImages where imageID = "
+ imgId.ToString();
rdr = cmd.ExecuteReader();
if(rdr.HasRows){
rdr.Read();
image = (byte[])rdr["GraphicBlob"];
}
}
finally{
try{
rdr.Close();
conn.Close();
}
catch{}
}
}
Using the code
This can be called from a regular aspx or HTML page in the project, by simply adding an image tag.
<img src=DynamicImageFromDB.aspx?id=203>
There are no files to clean up from the file system after this process, as the images are generated virtually for each call.
Points of Interest
If I get enough queries on this one, then I can start writing another article about how to stuff the images in the database in the first place.