【发布时间】:2016-06-08 03:55:45
【问题描述】:
我遇到了一个关于图像大小的奇怪问题。
我制作了一个简单的应用程序,可以在数据库中存储和检索图像。当我从文件中读取图像时,它的大小以 kB(千字节)为单位,字节数组的长度也是如此。
有两个图片框。 pb1 用于存储,pb2 用于加载。
我的 store() 和 load() 方法如下:
注意:openConnState() 和 CloseConnState() 是关闭和打开连接的方法。并且 byte[] img_byte 和 imgfilelength = 0 是在类中公开定义的。
商店:
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);
}
}
加载:
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);
}
}
我使用上面给出的 storeDB() 方法将图像存储到数据库中,但是当我使用上面给出的 load() 方法检索图像时,我收到一条错误消息,提示 参数无效。我发现问题可能与字节数组的长度有关,因为当我将数据库的'image'数据类型值检索到字节数组中时,字节数组的长度将始终为13。
我什至运行了下面的查询来获取它在数据库中的大小,它仍然是相同的,即 13 个字节。
从 P_Id = 1 的 TableImg 中选择 len(Convert(varbinary(max), Image))
谁能告诉我,为什么?
【问题讨论】:
-
这是旧的但是...您基本上应该将图像转换为 base64 字符串然后存储字符串...dailycoding.com/posts/…
标签: c# sql-server database image winforms