I want to store images in one of my database tables. I set the column type as image in the table definition. I first try to write the images into the database by converting images into a byte array. Then I try to get it back from my database, but I always get an Argument Exception. Here is my code:

Image image = (Image)new Bitmap(@"C:\2go\My Pictures\untitled.bmp");

MemoryStream ms = new MemoryStream();

image.Save(ms, ImageFormat.Bmp);

byte[] bmpBytes = ms.ToArray();

SqlConnection connection = new SqlConnection(@"Data Source=;Initial Catalog=BPSBD;User ID=;Password=");


SqlCommand command = connection.CreateCommand();

command.CommandText = "update CONT_Employee set sigImage = '"+bmpBytes+"'";


command.CommandText = "select sigImage from CONT_Employee where ssn = '001463863'";

byte[] pixels = (byte [])command.ExecuteScalar();

MemoryStream stream = new MemoryStream(pixels,0,pixels.Length);

stream.Write(pixels,0, pixels.Length);

Image img = Image.FromStream(stream); This is where exception comes from

pictureBox1.BackgroundImage = img;


I guess I can't write to the database properly. There is no problem converting an image into a byte array. That works fine,but after that I am in trouble. It's been two days and I still couldn't find it. I checked many sites, but I couldn't solve my problem. Please help me

Re: Visual C++ General storing an image in database and retrieving it back.

Aleksandr Tokarev

1. This code written in C#, but the scope of the forum C++, so its out of the scope of the forum.


2. Result of this string: "update CONT_Employee set sigImage = '"+bmpBytes+"'" is "update CONT_Employee set sigImage = 'System.Byte[]'". It is no a byte conjuction. There is the name of the type, this is normal implementation of ToString method for complex types. Thus, when you fetch back your value and try to convert it to image you obtain an exception. Because, it's difficutl convert 'System.Byte[]' value to IMAGE.

3. Your update statement doesn't contain WHERE statement, so when you execute your code in ALL rows in CONT_Employee table in field sigImage contains the same value ASCII codes of 'System.Byte[]', you can check it by selecting converted values of sigImage column to varchar.

4. Your SQL commands are not parametrized. You don't use parameter binding. It's not good practice, because someone can make an SQL-injection, attack your database and you loose all your data. Or make unlikely action in your database, like insert special user with special pemissions in your database.