How to show images from database into Picture box?


In this article I am going to explain about how to show images from database to picture box. Here I have stored images in the bytes format in the database convert that image and show in picture box.

Description :


In my previous article I was explained how to show all images from folder to picture box control. Here I have explained in detail about how to show stored images (as a bytes) from database to picture box as slide show.

I have convert that pictures bytes to picture and stored in the folder user view all images in the picture box using that folder images. Providing Previous and Next options to see previous and Next images in the same folder.

Table structure


create table imgupload(ID int IDENTITY(1,1),cntnt varbinary(max))

Using InsertImageToTable() method to insert images in to that table for testing.

Design side

I have design the form with two buttons Previous and Next look like below
design

Server side


using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.IO;

namespace DisplayBytesImage
{
public partial class Form1 : Form
{
//Please change connection string using below code
SqlConnection sqlcon = new SqlConnection(@"Server=RAVI-PC\SQLEXPRESS;database=test;uid=xxxx;pwd=yyyy;");
SqlCommand sqlcmd = new SqlCommand();
ArrayList alist = new ArrayList();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
int i = 0;
int filecount = 0;

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
//For testing use below method to insert some images in that table to test
//InsertImageToTable();

//create temp directory to store files from database bytes
string tmppath = Path.GetDirectoryName(Application.ExecutablePath) + "\\tmpdir";
if (!System.IO.Directory.Exists("tmppath"))
{
System.IO.Directory.CreateDirectory(tmppath);
}

//Convert bytes into image and store in temperory path
sqlcon.Open();
sqlcmd = new SqlCommand("select * from imgupload", sqlcon); //change table name as per your record
da = new SqlDataAdapter(sqlcmd);
dt = new DataTable();
da.Fill(dt);
sqlcon.Close();

if (dt.Rows.Count > 0)
{
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
Byte[] byt = (Byte[])dt.Rows[i]["cntnt"]; //change here your field name instead of cntnt
System.IO.File.WriteAllBytes(tmppath + "\\" + i + ".jpg", byt);
}

//Specify Source folder path here
LoadImage(tmppath);
}
}
//Load images from temp directory to picture box
void LoadImage(string path)
{
System.IO.DirectoryInfo inputDir = new System.IO.DirectoryInfo(path);
try
{
if ((inputDir.Exists))
{

//Get Each jpg files from a source folder and stored in the arraylist
System.IO.FileInfo file = null;
foreach (System.IO.FileInfo eachfile in inputDir.GetFiles())
{
file = eachfile;
if (file.Extension.ToLower() == ".jpg")
{
alist.Add(file.FullName);
//Store file count here
filecount = filecount + 1;
}
}
//Initally show first image in the picture box
pictureBox1.Image = Image.FromFile(alist[0].ToString()); ;
i = 0;
}
}
catch (Exception ex)
{

}
}

private void btnNext_Click(object sender, EventArgs e)
{
//check next position image is have or not
if (i + 1 < filecount)
{
pictureBox1.Image = Image.FromFile(alist[i + 1].ToString());
i = i + 1;
}
}

private void btnPrevious_Click(object sender, EventArgs e)
{
//check previous position image is have or not
if (i - 1 >= 0)
{
pictureBox1.Image = Image.FromFile(alist[i - 1].ToString());
i = i - 1;
}
}

//Testing insert image in table
void InsertImageToTable()
{
try
{
sqlcon.Open();
byte[] cnt = null;
//Source directory to read files change path as per your system
DirectoryInfo di = new DirectoryInfo("D:\\imgfolder");
//if you want only jpg files then filter it
FileInfo[] ArrFi = di.GetFiles("*.jpg");
foreach (FileInfo fi in ArrFi)
{
cnt = FileToByteArray(fi.FullName);
sqlcmd = new SqlCommand("insert into imgupload values (@Img)", sqlcon);
sqlcmd.Parameters.Add("@Img", cnt);
sqlcmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{

}
finally
{
sqlcon.Close();
}
}
public byte[] FileToByteArray(string fname)
{
byte[] cnt = null;
try
{
System.IO.FileStream fs = new System.IO.FileStream(fname, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader br = new System.IO.BinaryReader(fs);
long tb = new System.IO.FileInfo(fname).Length;
cnt = br.ReadBytes((Int32)tb);
fs.Close();
fs.Dispose();
br.Close();
}
catch (Exception ex)
{
}
return cnt;
}
}
}

Source code:

Client Side: Form Design
Code Behind: C#

Conclusion

I hope this code snippet is help you to know about Display image from database in picture box.


Attachments

  • DisplayBytesImage (44356-73917-DisplayBytesImage.rar)
  • Comments

    Author: Sunil Jas05 Dec 2012 Member Level: Gold   Points : 0

    Thanks a lot for sharing this with us this is really a good stuff.


    Regards,
    J.Sunil Jas
    MouseBiz Infotech
    Chennai

    Author: Vinayak01 Dec 2013 Member Level: Bronze   Points : 1

    Am Getting error @ this line: System.IO.File.WriteAllBytes(tmppath + "\\" + i + ".jpg", byt);

    Error: the process cannot access the file because it is being used by another process. c#



  • 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: