我有一个SQLite数据库,一个表有一个很好的数量,如果图像,我在数据库大小方面遇到了一些问题,所以我将逻辑转换为将图像存储在一个文件夹中并检索所需的图像,所以我现在正在做的是试图获得存储在数据库上的所有图像并将其保存在文件夹中,但我得到了一个错误Out of memory
。
注意:在将图像插入数据库之前,我使用了compress方法来压缩图像,并且在检索图像时也使用了decompress方法。
下面是我的代码:protected void Save()
{
try
{
using (SQLiteDataReader reader = DBConn.ExecuteReader("Select ID,image from transfers", CommandType.Text))
{
while (reader.Read())
{
if (reader["image"] != DBNull.Value)
{
byte[] image = (byte[])reader["image"];
image = Decompress(image);
Image newImage = byteArrayToImage(image);
string path = string.Format(@"E:imagesCI-{0}.Jpeg", reader["ID"].ToString());
newImage.Save(path, ImageFormat.Jpeg);
}
}
}
MessageBox.Show("done");
}
catch (SQLiteException ex)
{
// Do some logging or something.
MessageBox.Show("There was an error accessing your data. DETAIL: " + ex.Message);
}
}
从字节
获取图像的方法public Image byteArrayToImage(byte[] bytesArr)
{
Bitmap newBitmap;
using (MemoryStream memoryStream = new MemoryStream(bytesArr))
{
using (Image newImage = Image.FromStream(memoryStream))
{
newBitmap = new Bitmap(newImage);
}
}
return newBitmap;
// I tried this code also.
//return (Bitmap)((new ImageConverter()).ConvertFrom(bytesArr));
}
这是解压方法
public static byte[] Decompress(byte[] data)
{
using (MemoryStream input = new MemoryStream(data))
using (MemoryStream output = new MemoryStream())
{
using (DeflateStream dstream = new DeflateStream(input, CompressionMode.Decompress))
{
dstream.CopyTo(output);
}
return output.ToArray();
}
}
我根据我从评论中得到的建议更改了代码,所以谢谢。
下面是最终代码:
protected void Save()
{
try
{
using (SQLiteDataReader reader = DBConn.ExecuteReader("Select ID,image from transfers", CommandType.Text))
{
while (reader.Read())
{
if (reader["image"] != DBNull.Value)
{
byte[] image = (byte[])reader["image"];
image = Decompress(image);
string path = string.Format(@"E:imagesCI-{0}.jpeg", reader["ID"].ToString());
File.WriteAllBytes(path, image);
}
}
}
MessageBox.Show("done");
}
catch (SQLiteException ex)
{
// Do some logging or something.
MessageBox.Show("There was an error accessing your data. DETAIL: " + ex.Message);
}
}
我改变了解压方法如下:
public static byte[] Decompress(byte[] inputData)
{
if (inputData == null)
throw new ArgumentNullException("inputData must be non-null");
MemoryStream input = new MemoryStream(inputData);
MemoryStream output = new MemoryStream();
using (DeflateStream dstream = new DeflateStream(input, CompressionMode.Decompress))
{
dstream.CopyTo(output);
}
return output.ToArray();
if (inputData == null)
throw new ArgumentNullException("inputData must be non-null");
}