需求:旧系统数据库 图片存的是进制。数据有13w条(历史原因)。需要把图片进制转换对应的图片保存到本地 新系统保存图片地址。。现在写一个小程序需要转换旧系统图片数据 winfrom
while (_isWhile)
{
sql= txtSql.Text.Replace(row, _nextRow).Replace(pagesize, txtRow.Text);
Logging.Instance.WriteEnqueue(null, sql);
var dt = GetImgData(sql);
if (dt == null)
{
//没有数据自动终止循环
_isWhile = false;
lblMsg.Text = "执行完成";
Logging.Instance.WriteEnqueue(null, lblMsg.Text);
return ;
}
for (int i = 0; i < dt.Rows.Count; i++)
{
//文件名
var imgName = dt.Rows[i][fileName];
//图片进制
var stream = dt.Rows[i][fileStream];
if (string.IsNullOrEmpty(stream.ToString()))
{
Logging.Instance.WriteEnqueue(null, imgName + "对应列数据为空");
continue;
}
byte[] imagebytes = (byte[])stream;
var filename = path + "\\" + imgName + ".jpg";
//问题出现在这里 如何解决呢?
using (MemoryStream ms = new MemoryStream(imagebytes))
{
Bitmap bmpt = new Bitmap(ms);
bmpt.Save(filename, ImageFormat.Jpeg);
}
GC.Collect();
Thread.Sleep(20);
_indexSuccess++;
}
_whileCout++;
_nextRow = (_whileCout * int.Parse(txtRow.Text)).ToString();
if (!string.IsNullOrEmpty(txtRowStrar.Text))
{
_nextRow = (_whileCout * int.Parse(txtRow.Text)+int.Parse(txtRowStrar.Text)).ToString();
}
lblMsg.Text = "当前循环次数"+ _whileCout;
GC.Collect();
Thread.Sleep(1000);
}
目前是分批读取数据 。但是这里
Bitmap 这块这样写我知道也有问题 不停的创建对象。 内存溢出。如何解决呢?
解决code:
复制代码
_indexSuccess = 0;
BtnImg.Enabled = false;
if (BtnImgVerification()) return;
Logging.Instance.CreateFile(txtPath.Text);
lblMsg.Text = "程序执行中.......";
Task.Factory.StartNew(() =>
{
ExceptionsHelp.Instance.ExecuteVoidFunc(() =>
{
var dr = DbHelperSql.ExecuteReader(txtSql.Text);
var ms = new MemoryStream();
while (dr.Read())
{
var imgName = dr[txtFileName.Text];
var stream = dr[txtFileStream.Text];
if (string.IsNullOrEmpty(stream.ToString()))
{
Logging.Instance.WriteEnqueue(null, imgName + "对应列数据为空");
continue;
}
byte[] imagebytes = (byte[])stream;
var filename = txtPath.Text + "\\" + imgName + ".jpg";
ms.Write(imagebytes, 0, imagebytes.Length);
using (FileStream fsWrite = new FileStream(filename, FileMode.Append))
{
fsWrite.Write(imagebytes, 0, imagebytes.Length);
};
ms.Position = 0;
_indexSuccess++;
}
ms.Dispose();
ms.Close();
dr.Close();
GC.Collect();
Logging.Instance.WriteEnqueue(null, _indexSuccess.ToString());
MessageBox.Show(_indexSuccess.ToString());
}, "BtnImg_Click", () =>
{
Method(BtnImg, x => x.Enabled = true);
});
});问题补充:解决了 之前是分段加载 用的dataset 错误提示是System.Drawing 提示内存不足
dudu 建议改成 SqlDataReader居然成功了。
奇怪的是dataset内存引起的为什么提示 System.Drawing 呢。目前解决这个问题了
图片转换导入成功44G

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3932/viewspace-3150002/ ,如需转载,请注明出处,否则将追究法律责任。