简体   繁体   中英

How to save picturebox image into mysql database without imagepath

i just wanted to know if it is possible to save images into the database without the image path like for example a default image already assigned into the picture box. This is the sample code that I used that requires an image location.

byte[] imageBt = null;
FileStream fstream = new FileStream(this.txtImage.Text, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imageBt = br.ReadBytes((int)fstream.Length);

conn.Open();
MySqlCommand command = new MySqlCommand("insert into images(image)values(@IMG)", conn);
command.Parameters.Add(new MySqlParameter("@IMG", imageBt));

reader = command.ExecuteReader();
MessageBox.Show("Saved");

while (reader.Read())
{

}

You can use MemoryStream to save image from PictureBox to byte array

    Image image = pictureBox.Image;
    MemoryStream memoryStream = new MemoryStream();
    image.Save(memoryStream, ImageFormat.Png);

    byte[] imageBt = memoryStream.ToArray();

other parts would be the same.

I have tried this one...

        MemoryStream ms = new MemoryStream();
        pictureBox1.Image.Save(ms, ImageFormat.Png);
        byte[] pic_arr = new byte[ms.Length];
        ms.Position = 0;
        ms.Read(pic_arr, 0, pic_arr.Length);

        conn.Open();
        MySqlCommand cmd = new MySqlCommand("insert into images(image, name)values(@img,@imgName)", conn);
        cmd.Parameters.AddWithValue("@imgName", txtName.Text);
        cmd.Parameters.AddWithValue("@img", pic_arr);
        int n = cmd.ExecuteNonQuery();
        conn.Close();
        MessageBox.Show("COmplete");

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