我正在编写代码以在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();
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句