简体   繁体   中英

unable to convert byte[] to image

I am trying to retrieve a picture stored in MS SQL Server database. The type of the column is image. My code is:

try
{
    SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
    SqlCommand cmd = new SqlCommand(string.Empty, con);
    cmd.CommandText = "select Picture from Person";
    con.Open();
    SqlDataReader dataReader = cmd.ExecuteReader();
    dataReader.Read();

    byte[] image = new byte[10000];
    long len = dataReader.GetBytes(0, 0, image, 0, 10000);

    using (MemoryStream stream = new MemoryStream(image))
    {
        stream.Seek(0, SeekOrigin.Begin);
        pictureBox1.Image = Image.FromStream(stream);
    }
    con.Close();
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

I am continuously getting ArgumentException as Parameter is not valid when I set the pictureBox1.Image property. I tried all the available solutions on the Internet but all in vain.

You are always using a 10000 byte array even if the image is smaller (or larger). Don't manually create the byte[] , the DataReader can provide the entire byte array if you ask for it.

byte[] image = reader.GetFieldValue<byte[]>(0);

If you are not using .NET 4.5 you can just ask for the field and cast it manually.

byte[] image = (byte[])reader.GetValue(0);

However the fact that you are only using the first column from the first row you don't need a DataReader at all, just use ExecuteScalar() instead. (I also am cleaning up your code to use proper using statements and switched your ex.Message to ex.ToString() to provide more info in the error dialog).

try
{
    using(SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString))
    using(SqlCommand cmd = new SqlCommand(string.Empty, con))
    {
        cmd.CommandText = "select Picture from Person";
        con.Open();

        byte[] image = (byte[])cmd.ExecuteScalar();

        using (MemoryStream stream = new MemoryStream(image))
        {
            pictureBox1.Image = Image.FromStream(stream);
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

Try this :

SqlConnection con = new SqlConnection(Properties.Settings.Default.ConnectionString);
SqlCommand cmd = new SqlCommand(string.Empty, con);
cmd.CommandText = "select Picture from Person";
con.Open();
SqlDataReader dataReader = cmd.ExecuteReader();
dataReader.Read();
byte[] image = new byte[10000];
long len = dataReader.GetBytes(0, 0, image, 0, 10000);
using (MemoryStream mStream = new MemoryStream(image))
{
    pictureBox1.Image = Image.FromStream(mStream);
}

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