Forum
 
ForumForumDiscussions and...Discussions and....Net framework ....Net framework ...HowTo: Send an image from the database direct to the browserHowTo: Send an image from the database direct to the browser
Disabled 
Previous
 
Next Next
New Post
 12/03/2008 22:13
 
 Modified By RichardHowells  on 17/02/2011 09:40:06

This code snippet allows you to extract an image from the database (sample code is for SQL Server) and beam it straight to the browser without it needing to touch the HDD on the server. There are numerous advantages to this.

  • all of the data is in the same place (the database)
  • when you do a backup you get all the data in one go. You do not need to mess about with hundreds of files in a set of random folders
  • the database understands transactions. The file system does not.

Enough! Here is the code. It is written as an HttpHandler to make it more lightweight. Given an EmployeeId as a parameter it will pull an employee photo from the Northwind database and send it straight out to the response stream.

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Web;
using System.Drawing;
using System.IO;

public class ImageServer : IHttpHandler {
    // Get image from database and send direct to browser
    public void ProcessRequest(HttpContext context)
    {
        SqlConnection cn = new SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True");
        cn.Open();
        using (cn)
        {
            using (SqlCommand cm = new SqlCommand("select photo from employees where EmployeeId = @id", cn))
            {
                cm.Parameters.AddWithValue("@id", context.Request.QueryString["Id"]);
                byte[] buf = (byte[])cm.ExecuteScalar();

                Bitmap bmp;
                using (MemoryStream ms = new MemoryStream())
                {
                    // This bizarre offset is only here because the Northwind database has a
                    // 78 byte header on the front of every image.  Yours does not have
                    // to do that!
                    int offset = 78;
                    ms.Write(buf, offset, buf.Length - offset);
                    ms.Seek(0, SeekOrigin.Begin);
                    using (bmp = new Bitmap(ms))
                    {
                        context.Response.ContentType = "image/gif";
                        bmp.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif);
                    }
                }
            }
        }
    }
 
    public bool IsReusable {
        get {
            return true;
        }
    }
}

How to use it. Place an image on your page. Set the image's src to point at the HttpHandler. Something like...

image src=ImagerServer.ashx?EmployeeId=2

When the image requests the 'resource' it will be fed with the bytes of the image just as if it had asked for a *.gif file. Instead of that data coming from a file on the server it comes from the HttpHandler. It works really sweetly.

Enjoy!


Cheers,
- Richard
If this post helped you over a problem, or taught you something new, please login and rate it. Ratings are in the drop down in the top left corner
New Post
 13/03/2008 22:41
 

SQL Server 2008 has from some nice improvements for storing large binary data in the database.  There's a new filestream data type that will let you store varbinary(max) data directly on the NTFS filesystem, while still maintaining transactional consistency.  This mitigates some of the performance issues with streaming large BLOBs from the database, and will support storing files larger than the varbinary(max) limit of 2Gb.

Disabled 
Previous
 
Next Next
ForumForumDiscussions and...Discussions and....Net framework ....Net framework ...HowTo: Send an image from the database direct to the browserHowTo: Send an image from the database direct to the browser

Forum Usage Guidelines

The forums are a place for all to exchange ideas and techniques, and to post and answer questions.  All are welcome to read, registration is required to post. 

If you learn somthing new, discover or acquire a new technique, then please take a moment to register and rate the post that just helped you.  This site does not send spam and it does not release your personal details.  Full details in the site privacy policy.

We have some simple posting guidelines to keep the forums a pleasant and informative environment.

  • No flames, no trolls
  • No profanity, no racism
  • Site management has the final word on approving or removing any thread, post, or comment
  • English language only please

 

Copyright 2002-15 by Dynamisys Ltd