我正在编写代码以在 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();
}
感谢@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();
最佳答案
与其分两步复制位图,不如一步复制。这样可以大大减少内存使用量,因为内存中不会同时有原始图像的两个副本。
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();
}
关于c# - 在 C# 中调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24748270/