我正在编写一个代码来调整C#中的JPG图像大小.我的代码需要大约6秒来调整20张JPG图像的大小.我想知道在C#中有没有更快的方法呢?任何改善这一点的建议都表示赞赏!
这是我现在的代码:
Bitmap bmpOrig, bmpDest, bmpOrigCopy;
foreach (string strJPGImagePath in strarrFileList)
{
bmpOrig = new Bitmap(strJPGImagePath);
bmpOrigCopy = new Bitmap(bmpOrig);
bmpOrig.Dispose();
File.Delete(strJPGImagePath);
bmpDest = new Bitmap(bmpOrigCopy, new Size(100, 200));
bmpDest.Save(strJPGImagePath, jgpEncoder, myEncoderParameters);
bmpOrigCopy.Dispose();
bmpDest.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
感谢@Guffa的解决方案.我将dispose()移出了foreach循环.更新和快速的代码是:
Bitmap bmpDest = new Bitmap(1, 1);
foreach (string strJPGImagePath in strarrFileList)
{
using (Bitmap bmpOrig = new Bitmap(strJPGImagePath))
{
bmpDest = new Bitmap(bmpOrig, new Size(100, 200));
}
bmpDest.Save(strJPGImagePath, jgpEncoder, myEncoderParameters);
}
bmpDest.Dispose();
Run Code Online (Sandbox Code Playgroud)
而不是分两步复制位图,而是一步到位.这样你可以减少内存使用量,因为你一次没有在内存中有两个oringal图像副本.
foreach (string strJPGImagePath in strarrFileList) {
Bitmap bmpDest;
using(Bitmap bmpOrig = new Bitmap(strJPGImagePath)) {
bmpDest = new Bitmap(bmpOrig, new Size(100, 200));
}
bmpDest.Save(strJPGImagePath, jgpEncoder, myEncoderParameters);
bmpDest.Dispose();
}
Run Code Online (Sandbox Code Playgroud)