locked
Convert BitmapSource -> Bitmap -> byte[] ->database -> byte[] -> Windowsform img RRS feed

  • Question

  • Hey!
    Would rly appreciate any help on this. I'm trying to save an image from a WPF document in my database and then when it's called in a Windows form, show the image in an image window. Basically, WPF image to database to Windowsform image. So I converted the bitmapsource to a bitmap, then to byte[] then saved it in my database, then later called the byte[] in my windows form, then used the .fromStream command to set it to an image.
    Problem is - It comes out wit error message "PARAMETER IS NOT VALID" when i try to set the WindowsForm image to the uncompressed bitmap. Here is the relevant code:

    CODE SNIPET:

    //This bit is from the WPF project. Here i'm tryin to convert a bitmapsource image to a drawing.bitmap and then save into my database
    BitmapSource bmp = e.Parameter as BitmapSource;
    System.Drawing.Bitmap bitmap;
    byte[] byteArray = new byte[0];

    if (bmp != null)
    {
       bitmap = ConvertBitmap(bmp);
       byteArray = ConvertByte(bitmap);

    //Code to save into database here...
    }

    private static System.Drawing.Bitmap ConvertBitmap(BitmapSource src)
            {
                int width = src.PixelWidth;
                int height = src.PixelHeight;
                int stride = width * ((src.Format.BitsPerPixel + 7) / 8);

                byte[] bits = new byte[height * stride];

                MemoryStream strm = new MemoryStream();
                BitmapEncoder encoder = new BmpBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(src));
                encoder.Save(strm);
                return new System.Drawing.Bitmap(strm);
            }

    public static byte[] ConvertByte(System.Drawing.Bitmap img)
            {
                    byte[] Array = new byte[0];
                    using (MemoryStream stream = new MemoryStream())
                    {
                        img.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        stream.Close();

                        Array = stream.ToArray();
                    }
                    return Array;
             }

    //Then we move on to the WindowsForms project where i retrieve the byte[] from the database and set an image to the data


                Byte[] picData = new Byte[0];
              //Retrieve data from database, put it in a DataSet ds and collect the picture from the row we want.
                picData = (Byte[])(ds.Tables["EmpData"].Rows[3]["PIC"]);

                MemoryStream picStream = new MemoryStream(picData);
                ipic1.Image = Image.FromStream(picStream);

    //where ipic1 is the picture windows form image i want to set the picture to. 


    Please please please, any help will be appreciated. Been fighting with this thing for days and got a deadline at the end of the day. Thanks in advance to everyone that tries to help =]
    Friday, June 19, 2009 9:06 AM

All replies

  • Do it this way:  BitmapSource --> MemoryStream (png or jpg) --> ToArray --> DataBase --> MemoryStream --> Bitmap
    Friday, June 19, 2009 9:39 AM
  • Uh, how would i go about that? I can't use the "img.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);" line if I use your method because BitmapSource doesnt have the .Save option. So how would I go about creating a memoryStream in png or jpg?

    Thanks
    Friday, June 19, 2009 10:09 AM
  • BitmapEncoder.Save
    Friday, June 19, 2009 10:14 AM
  • From what I can see BitmapEncoder.Save doesn't have the option to say which format you want. So I did it this way: 

    public static byte[] BitsourceToArray(BitmapSource bitmapSource)
            {
                BitmapEncoder encoder = new JpegBitmapEncoder();
                using (MemoryStream stream = new MemoryStream())
                {
                    byte[] bit = new byte[0];
                    encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                    encoder.Save(stream);
                    bit = stream.ToArray();
                    stream.Close();
                    return bit;
                }
            }

    Is that what you mean? Though when I do it with this code I still get the same error at the end...
    Friday, June 19, 2009 10:47 AM
  • The encoder you choose determines the format.  The code you posted returns an empty array.
    Friday, June 19, 2009 11:27 AM
  • So that *does* create a memorystream(jpeg) but you said it gives an empty array? Can you please explain why that is and how I can go about correcting it?

    Thanks

    Friday, June 19, 2009 11:31 AM
  • You're right.  But I don't see how when you dispose the stream.  I tried the following code which seems to be OK:

        private void button1_Click(object sender, RoutedEventArgs e)
        {
          BitmapFrame bf = BitmapFrame.Create(new Uri(@"D:\Temp\Keys.png"));
          byte[] b= BitSourceToArray(bf);
          //code to save and retrieve array from database.
          MemoryStream ms = new MemoryStream(b);
          Bitmap bmp = new Bitmap(ms);
    
        }
        public static byte[] BitSourceToArray(BitmapSource bitmapSource)
        {
          BitmapEncoder encoder = new JpegBitmapEncoder();
          using (MemoryStream stream = new MemoryStream())
          {
            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
            encoder.Save(stream);
            return stream.ToArray();
          }
        }
    But I think it should be:

        private void button1_Click(object sender, RoutedEventArgs e)
        {
          BitmapFrame bf = BitmapFrame.Create(new Uri(@"D:\Temp\Keys.png"));
          byte[] b= BitSourceToArray(bf);
          //code to save and retrieve array from database.
          MemoryStream ms = new MemoryStream(b);
          Bitmap bmp = new Bitmap(ms);
        }
        public static byte[] BitSourceToArray(BitmapSource bitmapSource)
        {
          BitmapEncoder encoder = new JpegBitmapEncoder();
          MemoryStream stream = new MemoryStream();
          encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
          encoder.Save(stream);
          return stream.ToArray();
        }

    OK.  It's OK because stream.ToArray() makes a copy.
    Friday, June 19, 2009 12:02 PM
  • I've been going through this but still can't understand why it keeps giving me that error. I have my picture...i save to database....but it gives me the error when i try to decompress and show it in the picturebox again. Please can you (or anyone else who happens to be following this thread) point out what i'm doing wrong here?

    Code to save into database
        
        byte[] Lfinger;
                Lfinger = ImageToByte(tpic1.Image);

                string query = "UPDATE EmpData SET Lfingerp='" + Lfinger + "' WHERE (ID=1)";

                MySqlCommand cmdupdate = new MySqlCommand(query, con);
        //con is a connection defined out of this snippet.
                try
                {
                    con.Open();
                    cmdupdate.ExecuteNonQuery();
                    
                }
                catch (Exception ex)
                {
                    con.Close();
                    MessageBox.Show(ex.Message);
                }
               
    public static byte[] ImageToByte(Image img)
            {
                MemoryStream stream = new MemoryStream();
                img.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                return stream.ToArray();
            }

    code to retrieve image

        DataSet ds = new DataSet();
                MySqlDataAdapter dapt = new MySqlDataAdapter("SELECT Lfingerp FROM EmpData", con);
                dapt.Fill(ds, "EmpData");
                int x = ds.Tables["EmpData"].Rows.Count;

                Byte[] picData = new Byte[0];
                picData = (Byte[])(ds.Tables["EmpData"].Rows[x-1]["Lfingerp"]);

                MemoryStream picStream = new MemoryStream(picData);
                tpic1.Image = Image.FromStream(picStream);


    Friday, June 19, 2009 2:17 PM
  • Hi,

    Could you be more specific?

    What is the error message? From which statement?

    Harry
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.
    Welcome to the All-In-One Code Framework! If you have any feedback, please tell us.
    Friday, June 26, 2009 2:13 AM