RSS

Category Archives: WPF

Save and Retrieve images in WPF From Database

Download Sourcecode

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using System.Drawing.Imaging;

namespace imageDBWPF
{

public partial class MainWindow : Window
{
DataSet ds;
string imageName;

public MainWindow()
{
InitializeComponent();
}

private void insertData()
{
if (imageName == "")
{
return;
}

try
{
//Initialize a file stream to read the image file
FileStream fs = new FileStream(@imageName, FileMode.Open, FileAccess.Read);
//Initialize a byte array with size of stream
byte[] imgByteArr = new byte[fs.Length];
//Read data from the file stream and put into the byte array
fs.Read(imgByteArr, 0, Convert.ToInt32(fs.Length));
fs.Close();

//Save binary data in database
string constr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\imageDB.mdf;Integrated Security=True;User Instance=True";
using (SqlConnection conn = new SqlConnection(constr))
{
conn.Open();
string sql = "insert into tbl_Image(id,img) values('" + textBox1.Text + "',@img)";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(new SqlParameter("img", imgByteArr));
int result = cmd.ExecuteNonQuery();
if (result == 1)
{
MessageBox.Show("Image Added");
refreshImageList();
}
}
}
}
catch (Exception ex)
{

MessageBox.Show(ex.Message);
}
}

private void refreshImageList()
{
try
{
string connstr = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\imageDB.mdf;Integrated Security=True;User Instance=True";

using (SqlConnection conn = new SqlConnection(connstr))
{
conn.Open();

using (SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM tbl_Image", conn))
{
ds = new DataSet("myDataSet");
adapter.Fill(ds);
DataTable dt = ds.Tables[0];

//Alternatively can fill data into a data table directly
//DataTable dt2 = new DataTable();
//adapter.Fill(dt2);

comboBox1.Items.Clear();

foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["id"].ToString());
}
comboBox1.SelectedIndex = 0;

}
}

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

private void button1_Click(object sender, RoutedEventArgs e)
{
try
{

FileDialog fldlg = new OpenFileDialog();
fldlg.InitialDirectory = Environment.SpecialFolder.MyPictures.ToString();
fldlg.Filter = "Image File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif";
fldlg.ShowDialog();
{

imageName = fldlg.FileName;
ImageSourceConverter isc = new ImageSourceConverter();
image1.SetValue(Image.SourceProperty,isc.ConvertFromString(imageName));

}

fldlg = null;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}

private void button2_Click(object sender, RoutedEventArgs e)
{
insertData();
}

private void button3_Click(object sender, RoutedEventArgs e)
{
DataTable dataTable = ds.Tables[0];

foreach (DataRow row in dataTable.Rows)
{
if (row[0].ToString() == comboBox1.SelectedItem.ToString())
{
//Store binary data read from the database in a byte array
byte[] blob = (byte[])row[1];
MemoryStream stream = new MemoryStream();
stream.Write(blob, 0, blob.Length);
stream.Position = 0;

System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
BitmapImage bi = new BitmapImage();
bi.BeginInit();

MemoryStream ms = new MemoryStream();
img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi.StreamSource = ms;
bi.EndInit();
image2.Source = bi;

}
}
}

}
}

 
14 Comments

Posted by on June 24, 2012 in WPF, XAML

 

Tags: ,