How to store and retrieve images from Access database using C#.NET windows application?


In this article I will explain about how to store and retrieve image from access database using C#.NET windows application. Images are stored in the database as bytes.

Description

In my previous articles I have explained in detail about How to store and retrieve images from Access database using ASP.NET? similar like that resource I have store image in the MS ACCESS database but here I am using C#.NET windows application I alter some of the code based on windows application.

First I have create table like below to store images
StrImageAccessDB


For example,

Here I have use OpenFileDialog control to get image files from user and convert that image in to bytes then stored in the MS ACCESS database using like below code.

Insert image into MS ACCESS Database table


private void btnInsert_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() == "")
{
MessageBox.Show("Please select image to upload into database");
return;
}

byte[] FileBytes = null;
string fname = textBox1.Text.Substring(textBox1.Text.LastIndexOf("\\") + 1, textBox1.Text.Length - (textBox1.Text.LastIndexOf("\\") + 1));
//First read bytes from image to insert into table
string path = textBox1.Text; //change your path here
FileStream FS = new FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
BinaryReader BR = new BinaryReader(FS);
long allbytes = new FileInfo(path).Length;
FileBytes = BR.ReadBytes((Int32)allbytes);
// close all instances
FS.Close();
FS.Dispose();
BR.Close();

//Insert into access database
con.Open();
cmd = new OleDbCommand("insert into imgupload(ImgName,Img) values (@Im, @Img)", con);
cmd.Parameters.AddWithValue("@Im", fname); //alter as per your requirement
cmd.Parameters.AddWithValue("@Img", FileBytes);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Image insert successfully","Insert Image into Access Database");
textBox1.Text = "";
}


Retrieve image from MS ACCESS Database table

Last inserted image show in picture box control using below code


private void btnRetrieve_Click(object sender, EventArgs e)
{
//Save Temporarily that image bytes in one location and give that path to picture box

con.Open();
cmd = new OleDbCommand("select * from imgupload where ID=(select max(ID) from imgupload)", con);
da = new OleDbDataAdapter(cmd);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["Img"] != DBNull.Value)
{
pictureBox1.Image = ByteArrayToImage((Byte[])dt.Rows[0]["Img"]);
}
}
con.Close();
}
Bitmap ByteArrayToImage(byte[] b)
{
MemoryStream ms = new MemoryStream();
byte[] pData = b;
ms.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(ms, false);
ms.Dispose();
return bm;
}


Full Source Code

I have design page in the page like below

From 1 Code Behind


using System.Data;
using System.Data.OleDb;
using System.IO;
namespace StrImageAccessDB
{
public partial class Form1 : Form
{
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Data\\Database1.accdb;");
OleDbCommand cmd;
OleDbDataAdapter da;
DataTable dt = new DataTable();
public Form1()
{
InitializeComponent();
}

private void btnOpen_Click(object sender, EventArgs e)
{
OpenFileDialog fDialog = new OpenFileDialog();
fDialog.Title = "Select file to be zip";
fDialog.Filter = "JPG Files|*.jpg|JPEG Files|*.jpeg";
if (fDialog.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fDialog.FileName.ToString();
}
}

// 1) Insert into access database
private void btnInsert_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() == "")
{
MessageBox.Show("Please select image to upload into database");
return;
}

byte[] FileBytes = null;
string fname = textBox1.Text.Substring(textBox1.Text.LastIndexOf("\\") + 1, textBox1.Text.Length - (textBox1.Text.LastIndexOf("\\") + 1));
//First read bytes from image to insert into table
string path = textBox1.Text; //change your path here
FileStream FS = new FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);
BinaryReader BR = new BinaryReader(FS);
long allbytes = new FileInfo(path).Length;
FileBytes = BR.ReadBytes((Int32)allbytes);
// close all instances
FS.Close();
FS.Dispose();
BR.Close();

//Insert into access database
con.Open();
cmd = new OleDbCommand("insert into imgupload(ImgName,Img) values (@Im, @Img)", con);
cmd.Parameters.AddWithValue("@Im", fname); //alter as per your requirement
cmd.Parameters.AddWithValue("@Img", FileBytes);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Image insert successfully", "Insert Image into Access Database");
textBox1.Text = "";
}

// 2) Retrieve image from database and display in picture box
private void btnRetrieve_Click(object sender, EventArgs e)
{
//Save Temporarily that image bytes in one location and give that path to picture box

con.Open();
cmd = new OleDbCommand("select * from imgupload where ID=(select max(ID) from imgupload)", con);
da = new OleDbDataAdapter(cmd);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
if (dt.Rows[0]["Img"] != DBNull.Value)
{
pictureBox1.Image = ByteArrayToImage((Byte[])dt.Rows[0]["Img"]);
}
}
con.Close();
}
Bitmap ByteArrayToImage(byte[] b)
{
MemoryStream ms = new MemoryStream();
byte[] pData = b;
ms.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(ms, false);
ms.Dispose();
return bm;
}
}
}


Output

The output of the above code is look like below image
StrImageAccessDB


Source Code

Here I have attached full source code for the same download it and test it.

Client Side : Form Design
Code Behind : C#

Conclusion

I hope that this article is help you to know about how to store and retrieve image from MS ACCESS database using windows form application.


Attachments

  • StrImageAccessDBWin (44434-1426-StrImageAccessDBWin.rar)
  • Comments

    Guest Author: asim08 Mar 2013

    its only working with data type auto number id when i want to retrieve image from database.My question is that why its not working with data type number.Because its give in error "parameter is not valid.please can any body help??

    Guest Author: Ravi19 May 2013

    Great Example, Appreciate and Thanks..

    Author: rajaguru28 Aug 2015 Member Level: Bronze   Points : 0

    Bitmap bm = new Bitmap(ms, false);

    error came this line

    parameter is not valid

    Author: Chirag28 Oct 2015 Member Level: Bronze   Points : 0

    i face the error on insert value for conversion of image into byte......how to solve that prolbem?



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: