1

I want to retrieve an image from my database, but when application is running, I always get an error

parameter not valid

This is my code:

void showPic()
{
    konek.Open();

    SqlCommand Show = new SqlCommand("Select Image from [Akun] where  Username = '" + username.Text + "'", konek);

    SqlDataReader baca = Show.ExecuteReader();
    baca.Read();

    if (baca.HasRows)
    {
        byte [] images = (byte [])baca[0]; //this is line error "parameter not valid"
        MemoryStream memo = new MemoryStream(images);
        pictureBox1.Image = Image.FromStream(memo);
    }

    konek.Close();
}
DAFDZIKHO
  • 9
  • 2
  • 4
    **WARNING:** Your code is **dangerous**. It is wide open to SQL injection attacks. Always, *always, **always*** parametrise your code. [Why do we always prefer using parameters in SQL statements?](//stackoverflow.com/q/7505808) – Thom A Dec 10 '22 at 14:44
  • The following may be helpful: https://stackoverflow.com/a/66616751/10024425 – Tu deschizi eu inchid Dec 10 '22 at 15:05
  • 1
    Which line is giving error? – jdweng Dec 10 '22 at 16:31
  • in line 12 error – DAFDZIKHO Dec 11 '22 at 10:28
  • If anywhere I would expect a _Parameter is not valid_ exception message to be raised from `Image.FromStream(memo)`. That can happen when the stream doesn't contain a supported graphic image format, or because it's running on a Linux/macOS system that doesn't have libgdiplus installed and configured correctly. Please [Edit](https://stackoverflow.com/posts/74753896/edit) your question to include the full exception message - as text, not screen shot(s). – AlwaysLearning Dec 11 '22 at 14:05

1 Answers1

1

This error usually occurs when you try to convert an object to a type that it isn't compatible with.

It seems like you're trying to convert the SqlDataReader object baca to a byte[] array, but baca doesn't contain an array of bytes.

To fix this, you need to get the actual data from the SqlDataReader object and then convert it to a byte[] array.

You could do this by using the GetBytes method of the SqlDataReader object and passing the index of the column that contains the image data.

if (baca.HasRows)
{
    // Get the image data from the SqlDataReader object
    byte[] images = (byte[])baca.GetBytes(0);
    MemoryStream memo = new MemoryStream(images);
    pictureBox1.Image = Image.FromStream(memo);
}
Jiale Xue - MSFT
  • 3,560
  • 1
  • 6
  • 21