CodeSnip: How to Read/Write an Image to Database in Binary Format
page 1 of 5
Published: 07 Dec 2006
Abstract
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
Feedback
Average Rating: 
Views (Total / Last 10 Days): 81067/ 51

Introduction

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.


View Entire Article

User Comments

Title: project   
Name: Ben
Date: 2013-01-07 11:41:16 AM
Comment:
Can U Share us the Project File . .
/ and the Connection() Class
Title: test   
Name: test
Date: 2012-12-08 5:26:45 AM
Comment:
tested
Title: sdf   
Name: fds
Date: 2012-10-22 10:27:21 AM
Comment:
dsfsdfsdf
Title: image   
Name: ravi
Date: 2012-05-18 6:53:13 AM
Comment:
hi
c#.net
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
Comment:
thanks for help me
Title: how to store image in asp.net to databse sql server   
Name: Ravi
Date: 2011-12-02 9:49:12 PM
Comment:
I want to store image,word file in asp.net to sql server datbase.how will this.


ravi_patna4001@yahoo.com
Title: To display saved MS word file from database   
Name: Ganesh Atkale
Date: 2011-09-14 5:12:36 AM
Comment:
I have saved .docx file in database. I want to display that saved binary data and want to display that file on page in asp.net. Kindly help me.

my email id is ganraj_atkale@yahoo.com
Title: Pls hlp me..?   
Name: Amir
Date: 2010-10-12 6:31:10 AM
Comment:
insert Image to Database in Binary Format ......
Title: source   
Name: mike
Date: 2010-01-18 10:44:43 AM
Comment:
Hey can we get the source code?

techker@gmail.com
Title: Author has already presented the source code   
Name: Grace
Date: 2009-12-03 5:18:56 PM
Comment:
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:

http://authors.aspalliance.com/SAcharya/Code_images.zip
Title: Waiting for help   
Name: Ame
Date: 2009-11-13 2:15:10 AM
Comment:
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
Comment:
I was trying to save image using access using vb.net 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
Comment:
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
Comment:
where is Connection class?
Title: Good   
Name: Sandeep
Date: 2009-08-22 3:15:32 AM
Comment:
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
Comment:
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
Comment:
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
Comment:
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
Comment:
Sorry I forgot to add that I'm using VB 2008 express edition and MS Access on a Microsoft Vista

Thanks
Jbenzin
Title: Good but having problem, help!   
Name: Jbenzin
Date: 2009-02-09 6:09:15 AM
Comment:
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.

Thanks
Jbenzin
Title: VB codeing   
Name: Navin
Date: 2009-01-10 10:06:31 AM
Comment:
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 glib162002@yahoo.co.nz
Title: Excellent   
Name: Indra Dev Misra
Date: 2009-01-05 7:44:18 AM
Comment:
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
Comment:
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
Comment:
hello every body, I want to save images or pictures into MS Access using visual basic language. Plz, help me.
Thanks
Title: good sample   
Name: ABDULAZIZ ALGHAMDI
Date: 2008-08-20 12:52:35 AM
Comment:
PLASE
can you help me how to do read image from database

byusing LINQ TO SQL VB2008

THANK YOU
Title: how to create picture scanner with croping in vb   
Name: ravikumar(prog)
Date: 2008-06-27 8:28:43 AM
Comment:
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
Comment:
Hi,

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
Comment:
Hi
I have form in vb.net, 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
Comment:
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
Comment:
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 cool....by 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 obeid_mirza@yahoo.com

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
Comment:
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
Comment:
Hello,
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
Comment:
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
Comment:
i need this code in java
Title: Sim   
Name: Asma
Date: 2008-01-25 12:29:29 AM
Comment:
Hello,
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
Comment:
Hi
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
Comment:
Hi,

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.

Thanks,
Roopa.
Title: Getting Error in Visual Studio 2005   
Name: Shahid Iqbal Khan
Date: 2007-11-08 2:00:34 AM
Comment:
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.

Thanks

Shahid Iqbal Khan
Title: Upload and display image in ASP   
Name: aruna
Date: 2007-09-24 2:25:59 AM
Comment:
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
Comment:
thx mr Sandeep Acharya
u have put good quality code
best regards for U
Title: Thanks   
Name: M ATIF ALI
Date: 2007-08-30 12:43:54 PM
Comment:
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
Comment:
what is this i'm unable to download
Title: Mr.   
Name: Sam
Date: 2007-08-23 3:52:46 AM
Comment:
check the code then let u know
Title: FLASHING ERRORS   
Name: Franklin Dsouza
Date: 2007-08-03 8:48:46 AM
Comment:
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
Comment:
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
Comment:
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
Comment:
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
Comment:
good
Title: Easy to understand   
Name: Amit Vibhute
Date: 2007-05-22 2:56:11 PM
Comment:
Its good
Title: Error   
Name: Krishna Reddy
Date: 2007-05-15 4:40:56 AM
Comment:
it is working good in vb.net 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
Comment:
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
Comment:
U R PERFECT
Title: Thanks   
Name: Chirag Darji
Date: 2007-04-09 2:14:38 PM
Comment:
Thanks for your post. You can find anothe way of doing this at,

http://chiragrdarji.wordpress.com/2007/03/05/storing-and-retrieving-image-in-sql-server/
Title: Good sample   
Name: anh do
Date: 2007-03-28 5:49:43 PM
Comment:
Thanks for the sample code
Title: thanks   
Name: bahgwat chouhan
Date: 2007-03-06 3:14:28 PM
Comment:
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
Comment:
Thank you Sandeep ...
For sending the code ...
Title: Printing in Word Document   
Name: Ramesh
Date: 2007-01-25 9:09:23 AM
Comment:
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
Comment:
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 : http://authors.aspalliance.com/SAcharya/Code_images.zip
Title: where in connection() method   
Name: krishna reddy
Date: 2007-01-23 8:05:33 AM
Comment:
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
Comment:
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);
try
{
// 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);
MyStream.Close();
}
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;
MyCommand.Parameters.Add(param1);
MyConnection.Open();
MyCommand.ExecuteNonQuery();
MyConnection.Close();


}

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);
MyConnection.Open();
SqlDataReader MyReader = MyCommand.ExecuteReader();
if (MyReader.Read())
{
byte[] m_MyImage = (byte[])MyReader["IMAGE_DATA"];
Response.BinaryWrite(m_MyImage);
}


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

And would you like to gimme ur personal mailing ID?

Thanks

Sandeep
Title: inserting an image using c#.net   
Name: bhavani
Date: 2006-12-28 6:22:52 AM
Comment:
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 application.here i have taken two textboxes n one picturebox for inserting an image for each record.so 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
Comment:
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
Comment:
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-2024 ASPAlliance.com  |  Page Processed at 2024-03-29 7:22:56 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search