0

I would like to insert image to my database. After clicking button the image should be retrieved from database and showed. How to do it?

Thats what I am sending to database:

    //Send my img
    private void SendImageMessageClicked(object sender, MouseButtonEventArgs e)
    {
       OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "Images PNG (.png)|*.png";
        if (openFileDialog.ShowDialog() == true)
        {
            string message = imageToByteArray(System.Drawing.Image.FromFile(openFileDialog.FileName)).ToString();

            if (con.State == System.Data.ConnectionState.Open)
                con.Close();

            con.Open();
            cmd.CommandText = "INSERT INTO messages VALUES(null, " + userId + ", " + secondUserId + ", '" + message + "', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "')";
            cmd.Connection = con;
            cmd.ExecuteNonQuery();
            writeMessage.Text = "";
            con.Close();
        }
    }

    // convert image to byte array
    public byte[] imageToByteArray(System.Drawing.Image imageIn)
    {
        MemoryStream ms = new MemoryStream();
        imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        return ms.ToArray();
    }

That is how I am trying to get it back:

        while (dr.Read())
        {
            BitmapImage image = new BitmapImage();
            MemoryStream stream;

            stream = new MemoryStream(Encoding.ASCII.GetBytes((string)dr[3]));
            image.BeginInit();
            image.StreamSource = stream;
            image.EndInit();

            imgMsg.Source = image;
        }
4
  • Why are you ASCII encoding the data? Commented May 5, 2022 at 22:58
  • You'll find a full example here Commented May 5, 2022 at 23:01
  • @McNets do answer in full (and perhaps with link, but not needed) why you think that would be a full example (did not look at link - but suggestion for answer) Commented May 6, 2022 at 1:00
  • It makes no sense to decode an image from file just to get back an encoded frame buffer. Just read the binary file content by File.ReadAllBytes(openFileDialog.FileName) and write that to the database. When you create a a BitmapImage from a Stream, make sure to close the Stream after decoding by putting it in a using block. You also have to set image.CacheOption = BitmapCacheOption.OnLoad; Commented May 6, 2022 at 5:43

1 Answer 1

-1

this is example code, how to INSERT image (u should use VARBINARY(MAX) type in column):

                 Image image = Image.FromFile(@"D:\test\pictures\react-redux.png");
                 byte[] imageAsByteArr = ImageToByteArray(image);
                 using (SqlCommand command = new SqlCommand("insert into ImageTable values(2,@binaryValue)", conn))
                 {
                     command.Parameters.Add("@binaryValue", SqlDbType.VarBinary, imageAsByteArr.Length).Value = imageAsByteArr;
                     command.ExecuteNonQuery();
                 }

code above is using ImageToByteArray(...):

https://stackoverflow.com/a/3801289/12262729

when it comes to retrieve this data, let read this answer:

https://stackoverflow.com/a/7724595/12262729

after u retrieved data, let convert it to image:

https://stackoverflow.com/a/27774058/12262729

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.