简体   繁体   中英

Is there any shortest way to retrieve and upload image from database using c# wpf?

I have this code below that works fine. I am trying to upload and retrieve image from my database from tutorial but when I modify it with data from my database, it keeps showing Argument exception to this part

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

with an error of for system.drawing dll

It can upload but can't show the image uploaded

    DataSet ds;
    string strName, imageName;
    string constr = "Data Source=192.168.0.102;Initial Catalog=db_RVManzan;User ID=RVMserver;Password=rvmadmin";
    public sample()
    {
        InitializeComponent();
        BindImageList();
    }

    private void btnBrowse_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();
            {
                strName = fldlg.SafeFileName;
                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 btnSave_Click(object sender, RoutedEventArgs e)
    {
        insertImageData();
    }

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

        foreach (DataRow row in dataTable.Rows)
        {
            if (row[1].ToString() == cbImages.SelectedItem.ToString())
            {
                //Store binary data read from the database in a byte array
                byte[] blob = (byte[])row[43];
                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;

            }
        }
    }

    private void insertImageData()
    {
        try
        {
            if (imageName != "")
            {
                //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));

                //Close a file stream
                fs.Close();
                string sql = "update Employees set Emppic ='" + imgByteArr + "'";
                SqlConnection conn = new SqlConnection(constr);
                conn.Open();
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.ExecuteNonQuery();

                MessageBox.Show("Image added successfully.");
                BindImageList();
                conn.Close();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    private void BindImageList()
    {
        try
        {
            using (SqlConnection conn = new SqlConnection(constr))
            {
                conn.Open();

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

                    cbImages.Items.Clear();

                    foreach (DataRow dr in dt.Rows)
                        cbImages.Items.Add(dr["Empid"].ToString());
                    cbImages.SelectedIndex = 0;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

Please let me know if I am unable to explain the questions. Thanks

The intermediate System.Drawing.Image is redundant. You could directly load a BitmapImage from blob by

BitmapImage bi = new BitmapImage();

using (var stream = new MemoryStream(blob))
{
    bi.BeginInit();
    bi.CacheOption = BitmapCacheOption.OnLoad;
    bi.StreamSource = stream;
    bi.EndInit();
}

image2.Source = bi;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM