从Sql Server中Image字段导出保存JPG格式 内存溢出的问题

whmjw whmjw 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
现在有一个客户,我们要换他们的软件,他们有会员,大概总共有20000多个,绝大部分都 有会员的图片,可原来的老程序放进去的好像是BMP格式的,占用的空间太大,他们的库容量是6G,图片占了绝大部分大概有5G,我现在要做的就是把他们数据库里图片导出来,并保存为JPG格式,不过我写的东西老是报内存溢出,请大家看一下代码有什么问题,谢谢
DataTable dt=Global.Query("select max(id)  from t_discount_card where photo is not null");
int totalcount=int.Parse(dt.Rows[0][0].ToString());//保存大的图片ID
int id=0;
string sql="";
for(;id<totalcount;)
{
if(id==0)
sql="select top 20 id,photo from t_discount_card where photo is not null order by id";
else
sql="select top 20 id,photo from t_discount_card where photo is not null and id>"+id.ToString()+"order by id";
if(totalcount==id) //如果是最后一个图片,则退出
return;
DataTable dt1=Global.Query(sql);
for(int count=0;count<dt1.Rows.Count;count++)
if(dt1.Rows[count]["photo"]!=System.DBNull.Value)
{
byte[] imgdata=((byte[])(dt1.Rows[count]["photo"]));
if(imgdata!=null && imgdata.Length>100)
{
MemoryStream myStream=new MemoryStream();
foreach(byte a in imgdata)
{
myStream.WriteByte(a);
}
if(File.Exists(Application.StartupPath+@"\pic\"+dt1.Rows[count]["id"].ToString()+".jpg"))
File.Delete(Application.StartupPath+@"\pic\"+dt1.Rows[count]["id"].ToString()+".jpg");
Image.FromStream(myStream).Save(Application.StartupPath+@"\pic\"+dt1.Rows[count]["id"].ToString()+".jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
myStream.Close();
myStream=null;
}
id=int.Parse(dt1.Rows[count]["id"].ToString());
}
dt1.Dispose();
GC.Collect();
}

我的思路是每20个图片的读并写入成文件,保存为JPEG格式,现在的问题是大概导出600多张图片后,就报内存溢出了
...全文
评论 5
收藏 已收藏
分享
返回顶部
whmjw
C# 111,129 成员 642,538 内容