RSS

Save and Retrieve images in WPF From Database

24 Jun

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;

}
}
}

}
}

Advertisements
 
14 Comments

Posted by on June 24, 2012 in WPF, XAML

 

Tags: ,

14 responses to “Save and Retrieve images in WPF From Database

  1. srinivas

    February 18, 2013 at 12:36 pm

    using System.Drawing.Imaging;

    ref needed but its getting error

     
    • Rajitha

      February 18, 2013 at 1:05 pm

      What is the error do you get?

       
      • prasanth

        January 12, 2016 at 4:41 pm

        how to save this in wpf application folder
        OpenFileDialog op = new OpenFileDialog();
        op.Title = “Select a picture”;
        op.Filter = “All supported graphics|*.jpg;*.jpeg;*.png|” +
        “JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|” +
        “Portable Network Graphic (*.png)|*.png”;
        if (op.ShowDialog() == true)
        {
        image1.Source = new BitmapImage(new Uri(op.FileName));
        photo.Text = Convert.ToString(image1.Source);
        }

         
  2. Emmao

    February 22, 2013 at 1:02 am

    Hi,

    very brilliant work!
    But how do retrieve and save in a folder all images in the sql server table stored as binary.
    Thank you.

     
  3. Jeff

    June 7, 2013 at 3:09 pm

    Hi

    After hours of looking through examples and finding none that fit his looked like the answer to my problem in trying to import an image field in my SQL Server DB into an Image control in a WPF app I am putting together. Alas, it comes up with two errors – both relating to the Drawing library. There is no System.Drawing.Imaging

    using System.Drawing;
    …….
    …….
    …….

    System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
    ……………………..
    ……………………..
    img.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);

    the error is ‘the type or namespace name ‘Imaging’ does not exist in the namespace ‘System.Drawing’ (are you missing an assembly reference?)

    I’m using VS2012 Express.

    Any clues – Am I overlooking something obvious?

    /////////////////////////////////////////////

    this is the code I’ve written – which runs but does not seem to carry the byte value into the memorystream.

    //////////////////////////////////////////////

    SqlDataReader reader = cmd1.ExecuteReader(CommandBehavior.CloseConnection );
    BitmapImage bitmap = new BitmapImage();
    if (reader.HasRows)
    {
    while (reader.Read())
    {
    MemoryStream ms = new MemoryStream((byte[])reader[“bytePicture”]);
    bitmap.BeginInit();
    bitmap.StreamSource = ms;
    picClient.Source = bitmap;
    bitmap.EndInit();
    }
    }
    else
    {
    picClient.Source = null;
    }
    picClient.UpdateLayout();
    bitmap = null;
    bitmap.StreamSource = null;

    I’m newish to c# btw,

    thanks in advance

     
    • Rajitha

      June 7, 2013 at 9:31 pm

      Hi!
      Did you add the required reference to your project?

       
      • Jeff

        June 8, 2013 at 12:19 pm

        Hi! Thanks for answering

        . Yes, after I wrote the note – I looked through the comments and found the one that mentioned that. So I included it in the references and now it compiles. Two things here though – I don’t understand why one needs to do that when I thought you include the Drawing library by the Using statement,

        The other thing now is I am doing something wrong – the picture is not updating. I am relatively new to C# – so forgive my ignorance !

        Here is what I have:

        byte[] blob = (byte[])reader[“bytePicture”];
        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();

        ms.Seek(0, SeekOrigin.Begin);
        bi.StreamSource = ms;
        bi.EndInit();
        picClient.Source = bi;

         
      • Rajitha

        June 8, 2013 at 5:45 pm

        Hi,
        It ‘s true that I have included the reference to my project. But it does not mean that I can run the solution in another computer in the same way. You should set copy local property true for your reference so that the project becomes independent of target run time. You should use CopyLocal=True if the reference is not contained within the GAC.

         
      • Jeff

        June 8, 2013 at 6:54 pm

        Thanks so much for that tip – I would not have realised that it would have been a problem!

         
      • Rajitha

        June 8, 2013 at 10:24 pm

        Hi Jeff,
        You ‘re welcome.

         
  4. A-Max Lee

    September 16, 2013 at 9:01 pm

    Hi, I downloaded the solution & have a try & I will like to say that nice work.
    All the uploading image work fine & can retrieve it back.
    I have a question that why every time when I close the wpf application & re-run again all the previous image during last session of run time are missing. Besides that when I open “Show definition data” & don’t have anything inside it. What the coz of this? Reply are welcome.

     
  5. Emin

    February 28, 2014 at 1:54 am

    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.IO;
    using System.Drawing;

    namespace probelesil
    {
    ///
    /// Interaction logic for MainWindow.xaml
    ///
    public partial class MainWindow : Window
    {
    public MainWindow()
    {
    InitializeComponent();
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {

    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
    db_sekilDataContext db = new db_sekilDataContext();

    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    openFileDialog1.ShowDialog();
    openFileDialog1.Filter = “jpg;*.jpeg;*.png|” + “JPEG (*.jpg;*.jpeg)|*.jpg;*.jpeg|”;
    openFileDialog1.DefaultExt = “.jpeg”;
    textBox1.Text = openFileDialog1.FileName;
    ImageSource imageSource = new BitmapImage(new Uri(textBox1.Text));
    image1.Source = imageSource;
    }

    private void button2_Click(object sender, RoutedEventArgs e)
    {
    db_sekilDataContext db = new db_sekilDataContext();
    tbl_sekilprob images = new tbl_sekilprob();
    images.photo = textBox1.Text;
    images.imagetobyte = File.ReadAllBytes(textBox1.Text);
    byte[] image = File.ReadAllBytes(textBox1.Text);
    db.tbl_sekilprobs.InsertOnSubmit(images);
    db.SubmitChanges();
    }

    private void button3_Click(object sender, RoutedEventArgs e)
    {

    db_sekilDataContext db = new db_sekilDataContext();
    tbl_sekilprob inage = new tbl_sekilprob();
    // tbl_sekilprob aa = (from s in db.tbl_sekilprobs where s.id == 8 select s).FirstOrDefault();
    var result = (from t in db.tbl_sekilprobs where t.photo==textBox1.Text select t.imagetobyte).FirstOrDefault();

    Stream StreamObj = new MemoryStream(result);
    BitmapImage BitObj = new BitmapImage();
    BitObj.BeginInit();
    BitObj.StreamSource = StreamObj;
    BitObj.EndInit();
    this.image1.Source = BitObj;
    }

    ERROR : Stream StreamObj = new MemoryStream(result);

    Error 1 The best overloaded method match for ‘System.IO.MemoryStream.MemoryStream(byte[])’ has some invalid arguments

    Error2 Argument 1: cannot convert from ‘System.Data.Linq.Binary’ to ‘byte[]’

     
  6. Nagaraj

    March 25, 2014 at 11:19 am

    i need wpf window code not form code for upload image,displaying uploaded image and copying that image to another forlder.

     
  7. Nirav Dalsaniya

    April 22, 2015 at 1:48 pm

    System.Drawing.Image img = System.Drawing.Image.FromStream(stream);

    Error in above Line:
    An unhandled exception of type ‘System.ArgumentException’ occurred in System.Drawing.dll
    Additional information: Parameter is not valid.

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: