Control to Display Binary Images in ASP.NET
Introduction
The RbmBinaryImage control will help you display images directly from your database. You could bind the Image field directly to the ImageContent property, also you could specify whether you want the display to be as a thumbnail or not and provide the thumbnail size.
Using the RbmBinaryImage Control
<httpHandlers> <add verb="GET" path="__RbmImageHandler.rbm" type="RbmControls.RbmImageHandler" /> </httpHandlers>
<%@ Register Assembly="RbmControls" Namespace="RbmControls" TagPrefix="Rbm" %>
you could either bind the control directly in the ImageContent Property, Also specify whether to display the image as a thumbnail. and specify an image to display when the ImageContent is empty
an alternative is to do that by code
RbmBinaryImage1.ImageContent = FileUpload1.FileBytes;
Using the Code
The Imagecontent Property Retrieves and store the image bytes in the ViewState also if the DisplayThumbnail property is set to true then it retrieves the thumbnail of the image
public byte[] ImageContent
{
get
{
byte[] imageBytes = ViewState["ImageContent"] as byte[];
if (!DisplayThumbnail)
return (imageBytes == null) ? null : imageBytes;
else if (imageBytes != null)
{
byte[] bytes = CreateThumb();
return bytes;
}
else
return null;
}
set
{
ViewState["ImageContent"] = value;
}
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (DesignMode)
return;
if (ImageContent != null)
{
if(string.IsNullOrEmpty(CacheKey))
CacheKey = "Rbm" + System.DateTime.Now.Ticks;
ImageUrl = String.Format("~/__RbmImageHandler.rbm?MimeType={0}&EnableCaching={1}&ImageContent={2}",
MimeType, EnableCachinge ? "1" : "0", CacheKey);
if(this.Context.Cache[CacheKey] == null)
this.Context.Cache[CacheKey] = ImageContent;
}
else if (ImageUrl == "" || ImageUrl == null)
{
ImageUrl = EmptyImageUrl;
}
}
public void ProcessRequest(HttpContext context)
{
#region Caching Properties
string cacheKey = context.Request["ImageContent"];
if (String.IsNullOrEmpty(cacheKey))
return;
bool enableCaching = false;
if (!String.IsNullOrEmpty(context.Request["EnableCaching"]))
Boolean.TryParse(context.Request["EnableCaching"], out enableCaching);
#endregion
#region Image Properties
string mimeType = context.Request["MimeType"];
if (string.IsNullOrEmpty(mimeType))
mimeType = "image/jpeg";
byte []imageData = context.Cache[cacheKey] as byte[];
#endregion
if (!enableCaching)
context.Cache.Remove(cacheKey);
context.Response.ContentType = mimeType;
context.Response.OutputStream.Write(imageData, 0, imageData.Length);
}
Share your Thoughts
If you liked the control or have any comments on it or features you want to place in it kindly share your thoughts here
Comments
63 Responses to “Control to Display Binary Images in ASP.NET”
Leave a Reply



Really awesome blog. I enjoyed reading this review from you. I found that you really update your site regularly that made me more interesting. I’ve bookmarked your site for my future use.
Thank you
sagar
Thanks so much
, hope you will enjoy it more in the future.
Hi,
This is a great control. I’m new to asp.net and I’m trying to get this to work since it is just what I need. It doesn’t look like a db is included in your download, so I get an error when I try to run your test app. It looks like there are only 2 db columns needed?
Thanks,
Gary
Hi, I have Placed the Database Script in the Zip File you can re download it again now.
Regards
Ramy
Many Thanks first of all.
Your control is incredibly useful. I’m trying to implement it into a current project that I built. The project compiles in Visual Studio 2008 the image and it’s thumb don’t show up? and I did some checking through the debugger. and the Image is saved into the SQL DB. and I’m doing the right stuff to pull it out again.
Here’s my code for pulling the image out of the DB:
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
byte[] barrImg = (byte[])rdr["EmployeePhoto"];
foreach (DataListItem dli2 in DataList1.Items)
{
RbmBinaryImage DynamicImage = (RbmBinaryImage)dli2.FindControl(”RbmBinaryImage2″);
while (rdr.Read())
{
byte[] barrImg = (byte[])rdr["EmployeePhoto"];
DynamicImage.ImageContent = barrImg;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Your code behind shows:
RbmBinaryImage1.ImageContent = FileUpload1.FileBytes;
Is there something different between FileUpload1.FileBytes? the byte[] I’m using?
It seems is just s syntax thing?
MISSION CONTROL WE HAVE LIFT OFF!!!!! A-HA MOMENT.
Dude I was missing:
in my web.config file.
again you’ve made my life a lot easier:
Hey Ramy,
I have the control inside a DataList and what it looks like it’s doing is caching one image and repeating the one image through out the DataList? is there a way to turn off the Image Caching?
D
Hi, Could you send me a sample page with your code to check, since it shouldn’t be doing that the demo I made shows that to its using a DataList. so if you could send me the sample code to check it would be good. for disabling the caching you should just make the EnableCaching Property to false. if you want to disable the whole caching mechanism you will need to alter the image control itself.
Hey Ramy,
Heres the code block for the DataList:
//////////////////////////////////////////////////////////////////////////////////////////////
EmployeeInt:
<asp:Label ID=”EmployeeIntLabel” runat=”server”
Text=” />
First Name:
<asp:Label ID=”EmployeeFirstNameLabel” runat=”server”
Text=” />
Last Name:
<asp:Label ID=”EmployeeLastNameLabel” runat=”server”
Text=” />
Phone Directory:
<asp:Label ID=”EmployeePhoneDirectoryLabel” runat=”server”
Text=” />
Cell Number:
<asp:Label ID=”EmployeeCellNumberLabel” runat=”server”
Text=” />
Email:
<asp:Label ID=”EmployeeEmailLabel” runat=”server”
Text=” />
<Rbm:RbmBinaryImage ID=”RbmBinaryImage2″ runat=”server” DisplayThumbnail=”True” ImageContent=” />
/////////////////////////////////////////////////////////////////////////////////////////////////////
What’s happening is the images are loading, but if I hit Browser refresh, or scroll off screen up and down the images seem to start repeating? The DataList is rather large it has about 100 items in it?
Thanks Again,
Damon
Hi,
Well first you if you are going to load data dynamically in your code althought you could binded directly, you will need to remove the ImageContent attribute from the tag so will be
Then the way you are loading the data list is little bit wierd since you are making a nested loop on each data list item you loop for all items in the reader you have so you always assign the last item in the reader to all the controls below is the code I’m talking about that you posted previously
/************************************************/
//I See this line is of no use since you are not using it.
byte[] barrImg = (byte[])rdr["ImageContent"];
foreach (DataListItem dli2 in DataList1.Items)
{
// Here you retrieve the image control to place a content in it ok noprobs
RbmBinaryImage DynamicImage = (RbmBinaryImage)dli2.FindControl(”RbmBinaryImage2″);
//This is the second loop I’m talking about its weird cause you are looping on all the reader records and assigning to the same control which breaks the original wanted logic which should put the corresponded record value in the control so even if this reader has one record value then it will be the same for all controls which makes the duplication you are talking about
while (rdr.Read())
{
byte[] barrImg = (byte[])rdr["ImageContent"];
DynamicImage.ImageContent = barrImg;
}
}
/***********************************************/
I Recommend that you do it in one of three ways
1. Binded Directly <Rbm:RbmBinaryImage ID=”RbmBinaryImage2″ runat=”server” DisplayThumbnail=”True” ImageContent=’<%# Eval(”ImageContent”) %>’/>
2. In codein for bounded list in the ItemDataBound Event place the following code
protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
{
//ImageContent=’< %# Eval("ImageContent") %>‘
RbmBinaryImage DynamicImage = (RbmBinaryImage)e.Item.FindControl(”RbmBinaryImage2″);
if (DynamicImage != null)
DynamicImage.ImageContent = (byte[])((DataRowView)e.Item.DataItem).Row["ImageContent"];
}
3. If it is unbound data list I will modify your code a little bit to be
foreach (DataListItem dli2 in DataList1.Items)
{
RbmBinaryImage DynamicImage = (RbmBinaryImage)dli2.FindControl(”RbmBinaryImage2″);
byte[] barrImg = (byte[])//Here you place a call for a method or something that retrieves the required row data to display in thi sitem.
DynamicImage.ImageContent = barrImg;
}
also you could make it with your reader
to be
int index = 0;
while(reader.Read())
{
DataListItem dli2 = DataList1.Items[index];
RbmBinaryImage DynamicImage = (RbmBinaryImage)dli2.FindControl(”RbmBinaryImage2″);
byte[] barrImg = (byte[])rdr["ImageContent"];
DynamicImage.ImageContent = barrImg;
index++;
}
Hope this help if it doesn’t please send meyour page.aspx and page.aspx..cs to ramy.mostafa@gmail.com
Regards
Ramy
I bookmarked this site, Thank you for good job!
Hi Ramy, I have just downloaded your control and made a test page which consists of a gridview bound to am sqldatasource. The datasource returns the top 100 hunderd rows of my table, each row contains a photo. When i run the page all the data is returned correctly apart from all the photos are the same, how do i fix this?
Regards
Mick
PS Great Site
Hi Mick,
could you post your page code
Regards
Ramy
Hi Ramy, here is my page. There is nothing in the page behind
Untitled Page
<asp:Label ID=”Label1″ runat=”server” Text=”>
<asp:Label ID=”Label2″ runat=”server” Text=”>
<asp:Label ID=”Label3″ runat=”server” Text=”>
<Rbm:RbmBinaryImage EnableCachinge=”False” ID=”RbmBinaryImage1″ ImageContent=” runat=”server” />
<asp:SqlDataSource ID=”dsPictureTest” runat=”server” ConnectionString=”" SelectCommand=”Select top 100 RecognitionID, overviewimagedata, plate, LaneName, timestamp from recognitions left join lanes on recognitions.laneID = lanes.laneid order by recognitionid desc”>
Hi Mick,
try this
<Rbm:RbmBinaryImage EnableCachinge=”False” ID=”RbmBinaryImage1″ ImageContent=’<%# Eval(”overviewimagedata”) %>’ runat=”server” />
Regards
Ramy Mostafa
Hi Ramy, what has been posted on the screen in the above post doesn’t look like the code i pasted into the box. I’m not sure what the problem is there.
Mick
Hi Ramy, tried that and the result was the same, any more ideas?
thanks
Mick
Hi Mick,
It’s weird I will check in the code today and get back to you
Regards
Ramy
Hi Ramy, thanks for your time. I look forward to your reply.
Regards
Mick
Hi Mick,
I have done a test and it worked properly for me here is how my grid view look like
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” DataKeyNames=”ImageId” DataSourceID=”SqlDataSource1″>
<Columns>
<asp:BoundField DataField=”ImageId” HeaderText=”ImageId” InsertVisible=”False” ReadOnly=”True” SortExpression=”ImageId” />
<asp:BoundField DataField=”ImageTitle” HeaderText=”ImageTitle” SortExpression=”ImageTitle” />
<asp:TemplateField HeaderText=”BinaryImage”>
<ItemTemplate>
<Rbm:RbmBinaryImage ID=”RbmBinaryImage2″ runat=”server” DisplayThumbnail=”True” ImageContent=’<%# Eval(”ImageContent”) %>’ EmptyImageUrl=”images/NoPhoto.JPG” /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView>
Here is a screenshot of my grid

Regards
Ramy
Hi Ramy, I tried your code (the part that calls your control) and it worked, but, i had the same problem when i removed the DisplayThumbnail=”True” part.
Do you get the same problem?
Thanks
Mick
Hi Mick,
I have found yes a problem and I solved it try downloading the project again your problem should be solved now.
Thanks for your feedback
Regards
Ramy
cool sitename man)))
————————
sponsor: http://xabul.ru/
I got error….
There is no source code available for current location.
My image was not displaying so i was dubugging with F11 Key.
Any clue ?
I have project mahapages.com. i have used your rbmcontrols in my project.
it is working properly in visual sudio but when i publish my project; it doesn’t show image
please reply asap
Hi Naish,
Have you downloaded the last version if not please download the current version in the site. Then where do you place your break point if you want to check the display put the break point in the class that inherits from IHttpHandler, if you want to debug the control it self put the debug point in the place you want to see in the control class.
Regards
Ramy
Hi Sagar,
Please make sure you have the latest version as the initial version had a problem. If you do have the latest version please paste your code here to check or send me the .aspx and .cs page on my email if you don’t want to share it global at
ramy.mostafa@gmail.com, nevertheless it’s weird that it works on the visual studio and not in production cause it should be the same. what is displayed for you.
Regards
Ramy
Hi Sagar,
Also please make sure that you add the handler in the web.config
Regards
Ramy
Nice work! I’ll have to do a cross post on this one
Very nice site!
Wonderfull…
Hi Ramy, I’m having the same problem as Sagar. My code works fine in Visual Studio (application developed on my C:\ drive) but when i copy the code to the server the pictures don’t appear. I have the latest version of the code.
Thanks
Mick
Hi… Just wanted to say that this is an awesome control and you have saved me a lot of time!
The only problem is, I’m having the same problem as Mick and Sagar… when publishing it doesn’t show the images. Hope you get back to us soon.
Thanks,
Cindy
Hi,
I am happy to see that the control is useful, I’ll check the problem next Tuesday. so I hope that I come up with the solution the same day.
Regards
Ramy
Thanks for the reply… found the problem. Note I am working on Vista. When using IIS to run the application you need to register the handler for the project. To do that:
1. Open IIS and open the properties for the website you want the handler to
work for.
2. Open Handler Mappings and select a file extension which is served by
ASP.Net, like .asax or .aspx and click edit.
3. Copy the file that’s used over there (it should be
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll).
4. Close the dialog and click Add Script Map… to add a new one. Here, put
the copied value in the right textbox and fill in .rbm as the extension you
want to be handled.
5. Next close all open boxes by clicking OK and you should be ready to go.
Thanks for the awesome control!
Hi Cindy,
Thanks for the solution
I would appreciate if Mick and Sagar try it and see if it works for them too, and get back to us.
Regards
Ramy
Hi Ramy, just tried Cindy’s solution and it didn’t work for me. I am running server 2003
Hi, Ok then I guess I’ll still have to check it on tuesday
Regards
Ramy Mostafa
After my last post I noticed that there is a new line of code in my web.config file. I looks something like this:
…
” path=”*.rbm” verb=”*” modules=”IsapiModule” scriptProcessor=”%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll” resourceType=”Unspecified” preCondition=”classicMode,runtimeVersionv2.0,bitness32″ />
I would assume that with this line added when deploying on another box it should run without configuring the IIS settings for the project agains.
Hi Ramy, did you have any luck with the code on Tuesday?
Mick
Hi Mick,
No, nevertheless I am having some free time today at night I will check it.
Regards
Ramy Mostafa
Hi,
I have to do a Galery but I can’t read Images with yor control
my Images are in a DB I have en BinaryData
my code is:
Página sin título
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”"
SelectCommand=”SELECT Id,Imagen,Titulo,Descripcion FROM [sart_artesanias]“>
<Rbm:RbmBinaryImage ID=”RbmBinaryImage2″ runat=”server” ImageContent=” />
and I have a class for read my tABLE UB THE DB the fields are
id,Titulo,Descripcion,Imagen
and I’m using a id for read the Image
the class is
public SqlBytes retornaImagen(int clave)
{
SqlBytes resultado = null;
// Create a connection.
using (SqlConnection connection =
this.GetDbConnection())
{
using (SqlCommand command =
new SqlCommand
(”SELECT Imagen FROM sart_artesanias WHERE id = @IdArtesania”,
connection))
{
// Pass the parameter.
command.CommandType = CommandType.Text;
command.Parameters.Add
(”@IsArtesania”, SqlDbType.Int).Value = clave;
using (SqlDataReader reader =
command.ExecuteReader(
CommandBehavior.SequentialAccess |
CommandBehavior.SingleResult |
CommandBehavior.SingleRow))
{
if (reader.Read())
{
// Start reading the data.
SqlBytes photoData =
reader.GetSqlBytes(0);
if (!photoData.IsNull)
{
// Assign the data to the photoPictureBox control.
//this.photoPictureBox.Image =
// Image.FromStream(photoData.Stream);
resultado = photoData;
}
}
}
}
}
return resultado;
}
}
and the code behind is
using System;
using System.Data;
using System.Data.SqlTypes;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using Imagen;
using System.Drawing;
using System.IO;
using System.Collections.Generic;
using RbmControls;
using System.Web.UI.WebControls.Adapters;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ //hacemos la instancia de la clase para obtener los datos
//LectordeImagen li=new LectordeImagen();
//////le asignamos como datasource el dataset de la clase
////this.dtlArtesanias.DataSource = li.datosproductos();
////se llena el objeto
//this.dtlArtesanias.DataBind();
// //RbmBinaryImage1.ImageContent = FileUpload1.FileBytes;
// RbmBinaryImage im = new RbmBinaryImage();
// im.ImageContent = li.retornaImagen(1);
//
}
protected void dtlArtesanias_ItemDataBound(object sender, DataListItemEventArgs e)
{
//ImageContent=”
LectordeImagen li = new LectordeImagen();
RbmBinaryImage DynamicImage = (RbmBinaryImage)e.Item.FindControl(”RbmBinaryImage2″);
if (DynamicImage != null)
DynamicImage.ImageContent = (byte[])((DataRowView)e.Item.DataItem).Row["Imagen"];
//SqlByte)((int)li.retornaImagen(1))];
}
}
the result is a DataList with Titulo, Descripcion but not Image
I need help Ramy
Hi Luis please check comment number 10 and 11 on this post I have described in detail how to use the control
Hi Mick,
Iam working on it I will try to make something that won’t use the HTTP handler some how. I’ll get back to you with the result by tomorrow night my time.
Regards
Ramy
Great solution! Saved me a great deal of time for a project. Keep up the good work.
Thanks for usefull informatiom.
I had the same issue in which the images would not display on the production server (Win2003, IIS6) but it worked on my development machine with XP, VS2005.
I attempted the solution from CINDY on May 16th, 2009 of:
1. Open IIS and open the properties for the website you want the handler to
work for.
2. Open Handler Mappings and select a file extension which is served by
ASP.Net, like .asax or .aspx and click edit.
3. Copy the file that’s used over there (it should be
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll).
4. Close the dialog and click Add Script Map… to add a new one. Here, put
the copied value in the right textbox and fill in .rbm as the extension you
want to be handled.
5. Next close all open boxes by clicking OK and you should be ready to go.
And still no luck.
Eventually I figured out that Cindy’s solution will work, but you have to uncheck the option “Verify that file exists” when mapping the application extensions. (would be part of step 4 above)
Hopefully I save someone else from making the same silly mistake.
Regards.
Louis
I have just tried Louis’s method and it works great.
Thanks for that
Excellent control!
Mick
I have used this in my web project. It works fine when i run on visual studio 2008.
Image is not displayed when i put the website on the web server.
Please assist.
Thanks
Avinesh
Hi Ramy,
I’m trying to use your Rbmcontrols for image handling, but I have a problem converting the uploaded image (in byte[] format) to the database attribute (of type Image) while databinding. In my ASPX, I’m using a LinqDataSource and a FormView (in an AJAX Tabcontainer), so I’m NOT using a DataList. Because of this, I don’t have OnItemDataBound property available, which is being used in your c# code. This makes it difficult for me to adopt your solution. Any suggestions? Please let me know if you need excerpt from my HTML and/or C# code.
Thanks in advance and regards,
Johan
Hi Avinesh,
Please check the comments you will find a solution to how to solve the problem on the production server
Regards
Ramy
Hi Johan,
Please post a sample of your code or send it to me on my email
ramy.mostafa@gmail.com
Regards
Ramy
Yes it worked:
Point executable to :
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll.
Extension: .rbm
Uncheck the option “Verify that file exist”
Thanks Team
In Detail:
Under IIS, for specific Website
Under Virtual Directory – Click Configuration
- Under Mapping
- Click Add
- Executable : c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll
- Extension: .rbm
- Limit: GET,HEAD,POST,DEBUG
Hi Ramy,
I downloaded the control and tried to use in my asp.net page.
I have an asp.net web application with SQL 2008 Database. I am using VB.NET code behind for my asp.net pages. I have stored images in my sql database which I want to display using your control during runtime.
Please help me how can I use to display images using your control on aspx page with vb.net code behind.
Hi Ramy, wonderful control, but i have just a little advice for new features, a new property to set the displaymode or resizemode of image…
If i set width and height of my control: (canvas size)
Possible values are:
Crop (the image will be trimmed)
Fit (the image will be sized to fit the given dimensions)
None (default)
I’m working on your code to do this…
Thanks Ramy, very useful control.
I was having the same issues as a lot of people with the production application not showing the image, but adding the handler to IIS worked a treat.
Thanks all, for saving me a lot of time and headaches.
Hey Matteo, Thanks please share the new code for the new features
with us
Regards
Ramy
Greetings from Portugal,
You’ve done an excellent job. It worked flawlessly in my web app. Thanks for sharing!
Regards,
Telmo Pestana
Hi Ramy, this control is very useful. I am facing only one problem. Please help me. I am using the control in GridView. I want to show a default image in your control when the value of image field is NULL in the database. I am getting a Red Cross when there is a NULL value for the imagecontent property. Please Help. I am waiting.
Hello Ramy,
I just wanted to say that this is a great control. It really helped me out. I really appreciate the blog as well as all the feedback, which has helped me out as well. Keep up the great work!