I'm facing an odd problem regarding image size.
I've made a simple application which stores and retrieves images in a database. When I'm reading an image from the file, its size is in kB(kilobytes) and so is the length of the byte array.
There are two pictureboxes. pb1 for storing, and pb2 for loading.
My store() and load() methods are given below:
note: openConnState() and CloseConnState() are methods for closing and opening connections. And the byte[] img_byte and imgfilelength = 0 are defined publicly in the class.
Store:
private void StoreImage(string ChosenFile)
{
try
{
//MemoryStream ms = new MemoryStream();
//pb1.Image.Save(ms, ImageFormat.Jpeg);
//img_byte = new byte[ms.Length];
//ms.Position = 0;
//ms.Read(img_byte, 0, img_byte.Length);
FileInfo fileImage = new FileInfo(ChosenFile);
imgfilelength = fileImage.Length;
FileStream fs = new FileStream(ChosenFile, FileMode.Open, FileAccess.Read, FileShare.Read);
img_byte = new Byte[Convert.ToInt32(imgfilelength)];
int count, sum = 0;
while ((count = fs.Read(img_byte, 0, Convert.ToInt32(imgfilelength))) > 0)
{
sum += count;
}
//int byteread = fs.Read(img_byte, 0, Convert.ToInt32(imgfilelength));
fs.Close();
}
catch (Exception e)
{
throw e;
}
}
public void storetoDB()
{
OpenConnState(conn);
string str = "use db2 \n insert into TableImg(Image) \n values('" + img_byte + "')";
SqlCommand cmd = new SqlCommand(str, conn);
try
{
cmd.ExecuteNonQuery();
}
catch (Exception e)
{
throw e;
}
finally
{
CloseConnState(conn);
}
}
Load:
public void Loadimg()
{
try
{
pb2.Image = null;
byte[] getbyte = LoadImagefromDB(3);
using (MemoryStream ms = new MemoryStream(getbyte))
{
pb2.Image = Image.FromStream(ms);
}
pb2.Refresh();
}
catch (Exception e)
{
throw e;
}
}
public byte[] LoadImagefromDB(long pid)
{
byte[] img = null;
OpenConnState(conn);
string str = "use db2 \n select Image from TableImg where P_Id = " + pid;
SqlCommand cmd = new SqlCommand(str, conn);
try
{
img = (byte[])cmd.ExecuteScalar();
return img;
}
catch (System.Exception e)
{
throw e;
}
finally
{
CloseConnState(conn);
}
}
I store the image into a database using the storeDB() method given above, but when I retrieve the image using the load() method given above, I get an error saying parameter invalid. I found out the problem is likely to be related to the length of the byte array, because when I retrieve the 'image' datatype value of database into a byte array, the length of byte array will always be 13.
And I even ran the below query to get its size in database, it is still the same, i.e. 13 bytes.
select len(Convert(varbinary(max), Image)) from TableImg where P_Id = 1
Can anyone tell me, why?