Sunday, June 24, 2012

Save and Retrieve images in WPF From Database



Download Sourcecode

[sourcecode language="csharp"]
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;

}
}
}

}
}

[/sourcecode]

14 comments:

  1. using System.Drawing.Imaging;



    ref needed but its getting error

    ReplyDelete
  2. 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.

    ReplyDelete
  3. 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

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

    ReplyDelete
  5. 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;

    ReplyDelete
  6. 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.

    ReplyDelete
  7. Thanks so much for that tip - I would not have realised that it would have been a problem!

    ReplyDelete
  8. 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.

    ReplyDelete
  9. 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[]'

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

    ReplyDelete
  11. 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.

    ReplyDelete
  12. 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);
    }

    ReplyDelete

How to enable CORS in Laravel 5

https://www.youtube.com/watch?v=PozYTvmgcVE 1. Add middleware php artisan make:middleware Cors return $next($request) ->header('Acces...