简体   繁体   中英

“parameter is not valid” while converting bytes to image using c#

I saved my image to MySql Database using wamp server localhost but when i am trying to retrieve image from MySql and convert the image from bytes to image it gives the error parameter is not valid, i used many techniques and many solution but in vain, i user image converter and memory stream but didn't wok for me i am pasting my code please help me its very important.

byte[] img;

MySqlCommand cmd_image = new MySqlCommand("Select image from logindetails where Username = '" + txtUsername.Text + "'", con);
MySqlDataReader Image_Reader = cmd_image.ExecuteReader();
            while (Image_Reader.Read())
            {
                img = (byte[])Image_Reader["Image"];
            }

            System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
            Image image = (Image)converter.ConvertFrom(img);
            pictureBox1.Image = image;

ImageConverter is used to convert images, not create them. Use the code below:

    Bitmap bitmap;
    using (MemoryStream memoryStream = new MemoryStream(img))
    {
        using (Image imageFromStream = Image.FromStream(memoryStream))
        {
            bitmap = new Bitmap(imageFromStream);
        }
    }
    pictureBox1.Image = bitmap;

Note that if your byte array does not hold an image you will still get the same error.

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