CodeSnip: How to Read/Write an Image to Database in Binary Format
Published: 07 Dec 2006
In the code snippet we will see how to save the image files directly into the database without storing them physically in folders using Visual Basic .NET and MS Access as database.
by Sandeep Acharya
Average Rating: 
Views (Total / Last 10 Days): 95971/ 147


In the world of software development, most of the time we are asked to display some descriptive images to end user at UI.  Generally, developers store the images inside the folders as image files and display them at the time of demand.  In this case we need to store the physical path only in the database and the image file keeps staying inside the folder.  This may reduce the database size, but at the same time, it leads to occupying a huge disk space for storing images and also makes the image files publicly accessible.

So let us have a look at the solution to it.  In the code snippet given below we will see how we can save the image files directly into the database omitting the intermediate disk/folder space. One can find many solutions in this scenario using .Net and SQL Server as the database where we can make use of Stored Procedures.  Here we have used Visual Basic .Net and MS Access (as database).  So we are left with no option for using Stored Procedures.  The required code snippets are given below.

System Requirements

·         Microsoft XP Professional

·         Visual Studio .NET 2003 or Visual Studio 2005

Code Snippet

As we have discussed, the given code snippet will never keep the stored image in the folder/disk space.  We will also see both the read and write operations here.

Listing 1

Dim img As Image
Private Sub imgFile_FileOk(ByVal sender As System.Object, _
                           ByVal e As System.ComponentModel.CancelEventArgs) _
                           Handles imgFile.FileOk
  img = Image.FromFile(imgFile.FileName)
  btnSave.Enabled = True
  picBox.Image = img
  Catch ex As Exception
  If InStr(UCase(ex.Message), UCase("Out of memory")) Then
    MsgBox("Please select images only", _
           MsgBoxStyle.OKOnly, "Error Occured")
  End If
  End Try
End Sub


The code snippet given above only displays the image selected from the Dialog box in the picture box at UI.  The code is written inside the Try-Catch Block and, therefore, it also ensures the selection of image files only.

Now let us have a look on the gist.  The code given below is actually inserting the image into the database in binary format.

Listing 2

Private Sub btnSave_Click(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) Handles btnSave.Click
  Dim oConn As OleDb.OleDbConnection
  Dim oComm As OleDb.OleDbCommand
  Dim Err As String
  Dim sInsertQuery As String
  Dim FSO As New System.IO.FileStream(imgFile.FileName, _
                                      IO.FileMode.Open, IO.FileAccess.Read)
  sInsertQuery = "insert into images([image]) VALUES(?)"
  oConn = New OleDb.OleDbConnection( _
          New Connection().getConnectionString)
  oComm = New OleDb.OleDbCommand(sInsertQuery, oConn)
  Dim imgArrayByte(CType(FSO.Length() - 1, Integer)) As Byte
  FSO.Read(imgArrayByte, 0, imgArrayByte.Length)
  Dim QueryParameter As New OleDb.OleDbParameter("@Picture", _
                                                 OleDb.OleDbType.LongVarBinary, _
                                                 imgArrayByte.Length, ParameterDirection.Input, _
                                                 False, 0, 0, Nothing, DataRowVersion.Current, _
  MsgBox("Image is saved successfully to the Database", _
         MsgBoxStyle.OKOnly, _
         "Successfully Saved")
  btnSave.Enabled = False
  Catch Ex As Exception
  Err = Ex.Message
  MsgBox("Error : " & Err, _
         MsgBoxStyle.OKOnly, "Error Occured")
  oConn = Nothing
  oComm = Nothing
  End Try
End Sub


The code given above is actually inserting the images to the Database.  The above snippet needs a bit of clarification on some points, which are given below.

One can see the variable sInsertQuery is initialized as “insert into images([image]) VALUES(?).”  The reason is that we can not write the complete query here.  We need to add a parameter, which will hold the image in binary format, and this can only be done after converting the image to binary.  (Obviously, appending a parameter to the query cannot do this.)

For this reason we have used a placeholder [?] in the query which is replaced by the "QueryParameter" afterwards.

Creating a new OleDB Parameter requires an array of bytes.  For that reason we have used a File System Object and created the array of bytes out of it.

After successfully creating the parameter, it has replaced the placeholder [?] in the query and the query gets executed.

Until now we were looking into the codes, which is actually responsible for writing the images to the database.  Now, let us look into the section which is reading the images from the database.

Listing 3

Private Sub cmbImgIds_SelectedIndexChanged(ByVal sender As System.Object, _
                                           ByVal e As System.EventArgs) Handles cmbImgIds.SelectedIndexChanged
  btnDelete.Enabled = False
  Dim sQuery As New System.Text.StringBuilder()
  Dim oDataTable As New DataTable()
  Dim dtRow As DataRow
  Dim imagedata() As Byte
  Dim imageBytedata As MemoryStream
  sQuery.Append("SELECT image FROM images WHERE imageId = " & _
  oDataTable = New Connection().doDBconnection(sQuery.ToString, "Image")
  For Each dtRow In oDataTable.Rows
    btnDelete.Enabled = True
    imagedata = dtRow.Item("image")
    imageBytedata = New MemoryStream(imagedata)
  picBox.Image = Image.FromStream(imageBytedata)
End Sub


The above lines of codes are actually reading the image from the database in binary format and then displaying it in the picture box at UI.  A few points from the above lines of code are discussed below.

One needs to import the System.IO in order to access MemoryStream.

The Connection() is a user defined class that contains the public function doDBconnection().  The public function takes the Query and a proposed datatable name as input.  After executing the query it returns the results filled in a datatable with the proposed name.



We have seen how the images can be stored in the database in binary formats without keeping them in disk spaces as we used to do traditionally.  But of course, pros and cons are always there.  One cannot say that this method of storing images in a database is completely acceptable, but, yes, it is a different way of storing which can lead to the reduced use of disk space and keep the images safely restricting the public use of it.

User Comments

Title: project   
Name: Ben
Date: 2013-01-07 11:41:16 AM
Can U Share us the Project File . .
/ and the Connection() Class
Title: test   
Name: test
Date: 2012-12-08 5:26:45 AM
Title: sdf   
Name: fds
Date: 2012-10-22 10:27:21 AM
Title: image   
Name: ravi
Date: 2012-05-18 6:53:13 AM
how to read image from the local disk.
how to convert to binary format save in database sqlserver 2005
Title: For insert picture in oracle through java   
Name: faiyaz
Date: 2012-03-15 7:33:33 PM
thanks for help me
Title: how to store image in to databse sql server   
Name: Ravi
Date: 2011-12-02 9:49:12 PM
I want to store image,word file in to sql server will this.
Title: To display saved MS word file from database   
Name: Ganesh Atkale
Date: 2011-09-14 5:12:36 AM
I have saved .docx file in database. I want to display that saved binary data and want to display that file on page in Kindly help me.

my email id is
Title: Pls hlp me..?   
Name: Amir
Date: 2010-10-12 6:31:10 AM
insert Image to Database in Binary Format ......
Title: source   
Name: mike
Date: 2010-01-18 10:44:43 AM
Hey can we get the source code?
Title: Author has already presented the source code   
Name: Grace
Date: 2009-12-03 5:18:56 PM
Ame, the author has already indicated the place where you can download the source code. It works very fine. Thanks Sandeep. You can refer to the link below:
Title: Waiting for help   
Name: Ame
Date: 2009-11-13 2:15:10 AM
Is There any body who would Like to Help?

I fail To read Image from Db
for more Please read The comment below

Thanks a lot in advance
Title: Need Help   
Name: Ame
Date: 2009-11-12 7:24:53 AM
I was trying to save image using access using and I get
your Sample Code. But I fail to Read from the database

-Error occur on code
sQuery.Append("SELECT image FROM images WHERE imageId = " & cmbImgIds.SelectedItem)
Error- "Operator '&' is not defined for string "SELECT image FROM images WHERE i" and type 'DataRowView'"

and I can't undrstand how & what to do on Class Connection, Please could you provide me the full code on that Class?

Please help
Thanks in Advance
Title: image retriving   
Name: meenu
Date: 2009-10-08 5:27:19 AM
I am not able to retrieve image from databases as image in database is in binary form and i hav 2 show the image field in grid view and on selecting the row in grid view image should b displayed for updation plz solve my problem....
Title: Good   
Name: Nitin
Date: 2009-10-07 5:43:53 AM
where is Connection class?
Title: Good   
Name: Sandeep
Date: 2009-08-22 3:15:32 AM
But To insert an image into Access Database u didn't mention which datatype we need to choose in database
Title: urgent request   
Name: ravishankar
Date: 2009-07-15 2:04:40 AM
hi.. i need to upload and retrive images from sql server 2005 using vb from and to picture box.. can you plz send me the code snippet so that i can proceed further..

its most urgent and most important
Title: thanks.....   
Name: shashank
Date: 2009-05-27 4:16:19 AM
thnks for uploading ur code here ...but i m not retrive image propery so plz help me
Title: thanks   
Name: rsp
Date: 2009-02-21 2:15:45 AM
thank u very much sandeep for this artcle... really this is very useful to me... thanks again
Title: Good but having problem, help!   
Name: Jbenzin
Date: 2009-02-09 6:11:45 AM
Sorry I forgot to add that I'm using VB 2008 express edition and MS Access on a Microsoft Vista

Title: Good but having problem, help!   
Name: Jbenzin
Date: 2009-02-09 6:09:15 AM
Thanks for this code snippet Sandeep Acharya.
I'm trying to use it in my programme but I'm having a little problem. After adapting it, I get this error message:

"Type 'Connection' is not defined"

on these lines:
in listing 2

oConn = New OleDb.OleDbConnection( _
New Connection().getConnectionString)

and listing 3

oDataTable = New Connection().doDBconnection(sQuery.ToString, "Image")

I will be glad if you can help me out.

Title: VB codeing   
Name: Navin
Date: 2009-01-10 10:06:31 AM
I would like to have Visual Basic code for the same i.e. to load image from disk and store it to access database and again retriving it to use in the VB application.
Could you if possible mail me this code application to
Title: Excellent   
Name: Indra Dev Misra
Date: 2009-01-05 7:44:18 AM
Its work good but in onmly in 2003 but what changes should be apply in 2005
Title: image   
Name: shazmeen
Date: 2008-12-31 2:31:00 AM
i want to write some mater on image can u help me
Title: vijay kapoor   
Name: chhottu ghanari
Date: 2008-11-28 3:14:48 AM
hello every body, I want to save images or pictures into MS Access using visual basic language. Plz, help me.
Title: good sample   
Date: 2008-08-20 12:52:35 AM
can you help me how to do read image from database

byusing LINQ TO SQL VB2008

Title: how to create picture scanner with croping in vb   
Name: ravikumar(prog)
Date: 2008-06-27 8:28:43 AM
can please send the how to create pricture scanner in vb
and how to create crop control plz
Title: Reading the binary values from SQL Server 2000   
Name: Jagadeesh
Date: 2008-06-21 9:20:48 AM

My students details are storing in database, we are retriving very well, but records are in binary format. Then how can i covert binary data to string format

please help me...................
Title: Handling binary records with database   
Name: Jagadeesh
Date: 2008-06-21 9:06:14 AM
I have form in, that form accepts the students details of Number,Name,fee and inserting into the database.
But the Records are inserting in normal format but i want to insert the records in binay format. Please tell me the solution for that.
Title: how read image in Database   
Name: Ravikumar(Programer)
Date: 2008-06-21 3:01:04 AM
it nice but i neet this i am tring to the myself but, i need to help the these thing and i want to know about the
scanner drivers and how to crop the picture using picturebox
Title: How to Read/Write an Image to Database in Binary Format   
Name: Mirza Obeid Baig
Date: 2008-03-28 5:05:28 PM
this is cool and all but i can do all this as i have no idea what you all are talking about, i made my dadabase looking at microsofts msdn help. so if some one can help me by giving me step by step process like in in the msdn site that would be the way i have visual studios 2005 and the project that i am makeing a tool where we would save evaluations done for our team and have the agents name, date, managers name file number for the evluation, and etc so as to pull the image file.

any help to a newbew to all this would be great....

my yahoo id is

and for all those codeing gods out there i dont know codeing so this is not funny....
Title: How to select an Image from Database in Binary Format using java   
Name: priya
Date: 2008-03-25 2:14:04 AM
pls send code select an image from msaccess database in binary format using java.
Title: How to store an Image to Database in Binary Format in Sql-Server   
Name: Payal
Date: 2008-03-20 2:08:14 AM
Plz send me code in c# to run in Visual Studio 2005 for web-application.
Title: How to Read/Write an Image to Database in Binary Format   
Name: vicky
Date: 2008-02-29 3:05:41 AM
plz send code in access db and visual studio 2005 for windows application
Title: ss   
Name: ss
Date: 2008-02-11 12:33:05 AM
i need this code in java
Title: Sim   
Name: Asma
Date: 2008-01-25 12:29:29 AM
Handling 1st project in VB.Net 2005
I have 2 forms (Form1 & Form2)with access 2003 as backend.
In form1, I need to select image from system and store it into table1.
Next I need to retrieve the 'n' number of images that have been stored by form1 in form2 as a dropdown.
Title: Kar   
Name: Balabhadra
Date: 2008-01-18 3:17:00 AM
i am new in asp.i want to know,how can image save in ms access database and write image from database to html page.
it is very aurgent. Please help me
Title: Newbee   
Name: Roopa
Date: 2007-11-19 8:10:06 PM

I have around 200 photos on my remote server. I am in the process of changing the server and would like to download all the photos on my PC for backup. The photos are stored on the server in binary format. How can I download them at one shot without having to individually view each in the UI and then saving one at a time.

The site is a combination of ASP and MSSQL 2000.

Please help.

Title: Getting Error in Visual Studio 2005   
Name: Shahid Iqbal Khan
Date: 2007-11-08 2:00:34 AM
Hi Sandeep,

I am working on visual studio 2005 with access db, i am getting this error "Overload resolution failed because no accessible 'New' can be called without a narrowing conversion:".

Krishna Reddy also got same error, what was the resolution, kindly help.


Shahid Iqbal Khan
Title: Upload and display image in ASP   
Name: aruna
Date: 2007-09-24 2:25:59 AM
Hi Sandeep,
I am working on ASP.I don't know how to upload and display image in that page and insert into datyabase.
Can u suggest,i tried alot ..Ican insert into database but can't display ...
Title: Thnx   
Name: Ashutosh Agrahari
Date: 2007-09-18 2:07:07 AM
thx mr Sandeep Acharya
u have put good quality code
best regards for U
Title: Thanks   
Date: 2007-08-30 12:43:54 PM
Sir, i am very much thanks full to you for this artical.
i am in learning prossecc this artical is very helpfull for me
Title: Mr.   
Name: SAM
Date: 2007-08-23 3:55:43 AM
what is this i'm unable to download
Title: Mr.   
Name: Sam
Date: 2007-08-23 3:52:46 AM
check the code then let u know
Name: Franklin Dsouza
Date: 2007-08-03 8:48:46 AM
Hi that was a fine effort. But sorry to inform you that it is giving errors.
When I pass the MemoryStream object in FromStream method its throwing an exception Invalis Parameter used . Can You Help Me out . I am storing the Image in Access Database.
Title: ASP   
Name: aruna
Date: 2007-07-22 11:59:17 PM
How to insert .image file into access database in asp code
Title: ASP.NET   
Name: Simon Westwood
Date: 2007-07-06 4:44:05 AM
Have you got a tutorial that lets you do the same thing in ASP.NET VB.NET. I will need a full tutorial as I am new to this
Title: ASP.NET VB.NET   
Name: Simon Westwood
Date: 2007-07-06 4:24:52 AM
Hi Sandeep,

Have you got the same thing but for ASP.Net VB.NET. This tutorial would be greatly appreciated
Title: Image saving   
Name: Raj
Date: 2007-05-24 6:50:31 AM
Title: Easy to understand   
Name: Amit Vibhute
Date: 2007-05-22 2:56:11 PM
Its good
Title: Error   
Name: Krishna Reddy
Date: 2007-05-15 4:40:56 AM
it is working good in 2003
but in visual studio 2005 it raise an error
Error is

Error 11 Overload resolution failed because no accessible 'New' can be called without a narrowing conversion:
'Public Sub New(parameterName As String, dbType As System.Data.OleDb.OleDbType, size As Integer, direction As System.Data.ParameterDirection, precision As Byte, scale As Byte, sourceColumn As String, sourceVersion As System.Data.DataRowVersion, sourceColumnNullMapping As Boolean, value As Object)': Argument matching parameter 'precision' narrows from 'Boolean' to 'Byte'.
'Public Sub New(parameterName As String, dbType As System.Data.OleDb.OleDbType, size As Integer, direction As System.Data.ParameterDirection, precision As Byte, scale As Byte, sourceColumn As String, sourceVersion As System.Data.DataRowVersion, sourceColumnNullMapping As Boolean, value As Object)': Argument matching parameter 'scale' narrows from 'Integer' to 'Byte'.
'Public Sub New(parameterName As String, dbType As System.Data.OleDb.OleDbType, size As Integer, direction As System.Data.ParameterDirection, precision As Byte, scale As Byte, sourceColumn As String, sourceVersion As System.Data.DataRowVersion, sourceColumnNullMapping As Boolean, value As Object)': Argument matching parameter 'sourceColumn' narrows from 'Integer' to 'String'.
'Public Sub New(parameterName As String, dbType As System.Data.OleDb.OleDbType, size As Integer, direction As System.Data.ParameterDirection, precision As Byte, scale As Byte, sourceColumn As String, sourceVersion As System.Data.DataRowVersion, sourceColumnNullMapping As Boolean, value As Object)': Argument matching parameter 'sourceColumnNullMapping' narrows from 'System.Data.DataRowVersion' to 'Boolean'.
'Public Sub New(parameterName As String, dbType As System.Data.OleDb.OleDbType, size As Integer, direction As System.Data.ParameterDirection, isNullable As Boolean, precision As Byte, scale As Byte, srcColumn As String, srcVersion As Syste
Title: Image Saveing   
Name: Saghir Ahmed
Date: 2007-04-24 4:28:40 AM
This sample code is good and some of like me Programmer given good thingking
Title: perfect   
Name: Sevensea
Date: 2007-04-23 4:01:44 PM
Title: Thanks   
Name: Chirag Darji
Date: 2007-04-09 2:14:38 PM
Thanks for your post. You can find anothe way of doing this at,
Title: Good sample   
Name: anh do
Date: 2007-03-28 5:49:43 PM
Thanks for the sample code
Title: thanks   
Name: bahgwat chouhan
Date: 2007-03-06 3:14:28 PM
Hi thanks u have solved a major problem of us i.e. how to store data in binary format.................
Title: Re: krishna reddy   
Name: krishna reddy
Date: 2007-01-25 8:52:58 PM
Thank you Sandeep ...
For sending the code ...
Title: Printing in Word Document   
Name: Ramesh
Date: 2007-01-25 9:09:23 AM
Dear Friend.
I have to Print the Image to MS word document from the particular folder using browse option.can any one help me to do this...
Title: Re: Mr.Reddy   
Name: Reply for Mr.Reddy
Date: 2007-01-23 10:59:05 AM
Hello mr.Reddy,

Here is the link to download the complete code. I have mentioned it in the article at the time of submission but somehow it was missed by the ASP Aliiance team.

Link to download code :
Title: where in connection() method   
Name: krishna reddy
Date: 2007-01-23 8:05:33 AM
where is the code snippet of connection and dodbconnection()
please put it on this board
Title: For INSERT and SELECT Image File from database   
Name: kiran
Date: 2007-01-19 8:58:15 AM
private void Button1_Click(object sender, System.EventArgs e)

byte[] fileData = null;
if (File2 != null)
// Make sure the file has data.
if ((File2.PostedFile != null) && (File2.PostedFile.ContentLength > 0))
// Get the filename.
string fn = System.IO.Path.GetFileName(File2.PostedFile.FileName);
// Access the file stream and begin the upload. Store the file in a memory byte array.
Stream MyStream = File2.PostedFile.InputStream;
long iLength = MyStream.Length;
fileData = new byte[(int)MyStream.Length];
MyStream.Read(fileData, 0, (int)MyStream.Length);
catch (Exception excep)
//return false;

SqlConnection MyConnection=new SqlConnection("user id=xx;password=12345;database=northwind;server=xyz");
SqlCommand MyCommand = new SqlCommand("INSERT INTO MYTABLE (IMAGE_DATA) VALUES (@doc_content)", MyConnection);
SqlParameter param1 = new SqlParameter("@doc_content", SqlDbType.Image);
param1.Value = fileData;


private void Button2_Click(object sender, System.EventArgs e)
SqlConnection MyConnection=new SqlConnection("user id=xx;password=12345;database=northwind;server=xyz");
SqlCommand MyCommand = new SqlCommand("SELECT IMAGE_DATA FROM MYTABLE WHERE ID=" + Convert.ToInt32(Selectid.Text), MyConnection);
SqlDataReader MyReader = MyCommand.ExecuteReader();
if (MyReader.Read())
byte[] m_MyImage = (byte[])MyReader["IMAGE_DATA"];

Title: Reply for Bhavani   
Name: From Sandeep
Date: 2006-12-28 12:07:39 PM
Hello Bhavani,
Could you please send me your codes and SQL Table (And SPs if you have) to my yahoo id? Its :

And would you like to gimme ur personal mailing ID?


Title: inserting an image using   
Name: bhavani
Date: 2006-12-28 6:22:52 AM
hi sandeep,
i'm facin problem in insserting the image in the table. here i want to use csharp language in the front end and want to insert the image into the table through .net code by using Ms Sql. am not getting what code to write in query analyser and also what code to write in windows i have taken two textboxes n one picturebox for inserting an image for each can u plz help me by sending the code which i have to use in query analyser as well as in windows application
Title: Thanks to Dhaval   
Name: Sandeep Acharya
Date: 2006-12-07 2:55:28 AM
Hi Dhaval, I have no way to contact you so writing here only just with a hope if you can visit here again.

Thanks a lot for the idea. Your idea will certainly a better one for larger images. I'll try to implement this and if possible then get back to you.

Thanks a lot again...
-- Sandeep Acharya
Title: .NETPhreak   
Name: Dhaval Patel
Date: 2006-12-07 1:37:09 AM
Good article, Sandeep. I am not sure of a way to send data in chunks to insert a large image file without using stored procedures (in SQL Server we can use the UPDATE .WRITE method). But I think you can improve on your idea of selecting the image in chunks - it is more effecient that way. I have never worked with an Access DB, so this may be completely off the charts, but to read data in chuks you'd end up doing something like this:

const int BufferSize = 1024;
byte[] image = null;
using (SqlDataReader reader = command.ExecuteReader(CommandBehavior.SequentialAccess))
using (MemoryStream imageStream = new MemoryStream())
long currentIndex = 0;
byte[] buffer = new byte[BufferSize];
int bytesRead;
while (reader.Read())
currentIndex = 0;
bytesRead =(int)reader.GetBytes(0, currentIndex, buffer, 0, BufferSize);
while (bytesRead != 0)
imageStream.Write(buffer, 0, bytesRead);
currentIndex += bytesRead;
bytesRead =
(int)reader.GetBytes(0, currentIndex, buffer, 0, BufferSize);

if (imageStream.Length > 0)
image = imageStream.ToArray();

Of course, you'd have to convert this code to VB :).
Keep writing!

Community Advice: ASP | SQL | XML | Regular Expressions | Windows

©Copyright 1998-2021  |  Page Processed at 2021-12-02 8:36:20 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search