找的一个C#方法用于批量处理图片缩放,内存不足问题。
在网上找的一个批量处理图片缩放的方法。进行图片的批量处理。发现处理的张数最多只能一起处理2000多张,电脑就报内存不足了。下面是主要方法,求大神指导。
private void button1_Click(object sender, EventArgs e)
{
DirectoryInfo cuurDir = new DirectoryInfo(currentDirPath);
FileInfo[] files = cuurDir.GetFiles(); //返回当前目录的文件列表
StringBuilder builder = new StringBuilder("<ul>");
Parallel.ForEach(files, file =>
{
string oldFileName = file.FullName;
string newFileName = GetSaveDirPath("D:\\VSTS\\JuFine\\03_Code\\DataFeed" + "\\i801") + "\\" + file.Name;
Bitmap srcBitmap = null;
Bitmap destBitmap = null;
Graphics graphic = null;
try
{
int width = Convert.ToInt32(TxtWidth.Text);
int height = Convert.ToInt32(TxtHeight.Text);
width = width == 0 ? 100 : width;
height = height == 0 ? 100 : height;
GC.Collect(); GC.WaitForPendingFinalizers();
srcBitmap = new Bitmap(file.FullName); //加载原图
destBitmap = new Bitmap(width, height);
RectangleF srcRec = new RectangleF(0, 0, srcBitmap.Width, srcBitmap.Height);
RectangleF destRec = new RectangleF(0, 0, width, height);
graphic = Graphics.FromImage(destBitmap);
graphic.DrawImage(srcBitmap, destRec, srcRec, GraphicsUnit.Pixel);
destBitmap.Save(newFileName, System.Drawing.Imaging.ImageFormat.Jpeg);//保存较大Jpeg,如1280*1024图片时,比较消耗内存哦。
if (graphic != null) { graphic.Dispose(); graphic = null; }
if (destBitmap != null) { destBitmap.Dispose(); destBitmap = null; }
if (srcBitmap != null) { srcBitmap.Dispose(); srcBitmap = null; }
GC.Collect(); GC.WaitForPendingFinalizers();
}
catch (Exception ex)
{
if (graphic != null) { graphic.Dispose(); graphic = null; }
if (destBitmap != null) { destBitmap.Dispose(); destBitmap = null; }
if (srcBitmap != null) { srcBitmap.Dispose(); srcBitmap = null; }
GC.Collect(); GC.WaitForPendingFinalizers();
MessageBox.Show(ex.Message);
}
finally
{
FileInfo newFile = new FileInfo(newFileName);
builder.Append(string.Format(@"<li><img style='width:150px;height:200px;' alt='{0}' src='{1}' /><p>大小:{2}k</p></li>", newFile.Name, newFile.FullName, newFile.Length)).Append(Environment.NewLine);
}
});
builder.Append("</ul>");
string template = TemplateHelper.ReadTemplate(TemplateHelper.GetTemplateDirPath(), "template.htm");
List<MatchItem> itemList = new List<MatchItem>();
itemList.Add(new MatchItem("$(imglist)", builder.ToString()));
webBrowser1.DocumentText = TemplateHelper.AnalyzeTemplate(itemList, template);
LblResult.Text = string.Format("共计{0}张图片", files.Length);
MessageBox.Show("请在桌面images文件夹下查看!", "提示信息");
}