0

I'm getting a "Parameter is not valid" exception while running this code. I'm trying to display an image that comes from the database:

SqlConnection con = new SqlConnection("data source=.;Initial catalog=RMSDB;user=sa;password=....;");
con.Open();
string sql = String.Format("Select Emp_Pic_ImageData From Employees where Emp_Id='{0}'", TxtBoxId.Text);
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
    byte[] img = (byte[])(reader[0]);
    if (img == null)
    {
        PicboxEmployee.Image = null;
    }
    else
    {
        MemoryStream mstrm = new MemoryStream(img);
        PicBoxName.Image = Image.FromStream(mstrm); //error: "Parameter is not valid"
    }
}
else
{
    MessageBox.Show("this not exists");
}
Kobi
  • 135,331
  • 41
  • 252
  • 292
Slan
  • 545
  • 2
  • 6
  • 18
  • 6
    what exactly is `img`, where does it come from? – olydis Sep 12 '13 at 13:29
  • What is typeof(img) parameter – Tushar Chhabhaiya Sep 12 '13 at 13:29
  • 6
    *Here is an error "Parameter is not valid* Means `MemoryStream` doesn't have a valid image format. – Sriram Sakthivel Sep 12 '13 at 13:29
  • 1
    And what is the `img` variable. I mean, everyone can tell it is a `byte[]` but what is its story. Show us how it came to be in existence (The error may be where you say it is but the problem is elsewhere... and it has got something to do with the contents of `img`) – Eduard Dumitru Sep 12 '13 at 13:30
  • Is this a WinForm application? I'm not sure, so I didn't add the tag. – Kobi Sep 12 '13 at 13:42
  • 1
    Also - your code is subject to [Sql Injection](http://stackoverflow.com/q/332365/7586), you should use a [parameterized command](http://stackoverflow.com/q/5468425/7586). – Kobi Sep 12 '13 at 13:46
  • below i have posted both the codes that i am using – Slan Sep 13 '13 at 05:53

4 Answers4

1

The 'Parameter is not valid' error is occurring because the byte array you've fetched back from the database does not represent valid image binary data.

There are various reasons this might happen. As a start, take a look at the data in your database - it might not be storing the binary data you expect.

In the meantime, I've quickly thrown together a small console app that does what you're after:

class LoadImageFromDbSpike
{
    private const string ConnectionString = @"Data Source=[SERVERNAME];Initial Catalog=[DBNAME];Trusted_Connection=true;Connect Timeout=180;";
    private const string ImageOnDiskPath = @"c:\test.png";
    private const string OutputPath = @"c:\output.png";

    static void Main(string[] args)
    {
        var imageData = File.ReadAllBytes(ImageOnDiskPath);

        var imageId = StoreImageData(imageData);

        var imageDataFromDb = LoadImageData(imageId);
        File.WriteAllBytes(OutputPath, imageDataFromDb);
    }


    private static int StoreImageData(IEnumerable<byte> imageData)
    {
        const string insertCommand = "INSERT INTO ImageSpike (Image) " +
                                     "VALUES (@ImageData); " +
                                     "SELECT SCOPE_IDENTITY();";

        using (var con = new SqlConnection(ConnectionString))
        using (var cmd = new SqlCommand(insertCommand, con))
        {

            cmd.Parameters.AddWithValue("@ImageData", imageData);
            cmd.Connection.Open();

            return (int) (decimal) cmd.ExecuteScalar();
        }
    }

    private static byte[] LoadImageData(int id)
    {
        const string loadImageCommand = "SELECT TOP 1 Image FROM ImageSpike " +
                                        "WHERE Id = @Id; ";

        using (var con = new SqlConnection(ConnectionString))
        using (var cmd = new SqlCommand(loadImageCommand, con))
        {
            cmd.Parameters.AddWithValue("@Id", id);
            cmd.Connection.Open();

            var result = cmd.ExecuteScalar();
            return (byte[]) result;
        }
    }
}
Damon J. Murray
  • 115
  • 2
  • 7
0
//code for saving image into sql server 2008 r2//////
            byte[] img = null;
            FileStream fs = new FileStream(imgLoc,FileMode.Open,FileAccess.Read);
            BinaryReader br=new BinaryReader(fs);
            img = br.ReadBytes((int)fs.Length);


            string conn = "data source=.;Initial catalog=RMSDB;user=sa;password=ibs;";
            SqlConnection con = new SqlConnection(conn);
            con.Open();
            string cmdd = String.Format("INSERT INTO Employees (Emp_Pic_ImageData)  VALUES('{0}')",  @img);

            SqlCommand cmd = new SqlCommand(cmdd, con);

            cmd.Parameters.Add(new SqlParameter("@img",img));
            int tempss = cmd.ExecuteNonQuery();
Slan
  • 545
  • 2
  • 6
  • 18
0
//code for retrival of image from sql server////////////


            string sql = String.Format("Select Emp_Pic_ImageData From Employees where Emp_Id='{0}'", TxtBoxId.Text);
            SqlCommand cmd = new SqlCommand(sql, con);
            SqlDataReader reader = cmd.ExecuteReader();
            reader.Read();
            if (reader.HasRows)
            {
                byte[] img = (byte[])(reader[0]);
                if (img == null)
                {
                    PicboxEmployee.Image = null;
                }
                else
                {
                    MemoryStream mstrm = new MemoryStream(img);
                    PicboxEmployee.Image = new System.Drawing.Bitmap(mstrm); //there is error of parameter is not valid.

                }
            }
            else
            {

                MessageBox.Show("this not exists");

            }
Slan
  • 545
  • 2
  • 6
  • 18
-1

the problem is because, you are bringing it incorrectly from database. try change your code for this:

while (registry.Read())

{                
                byte[] image = (byte[])registry["Image"];    

}
Bob Swager
  • 884
  • 9
  • 25