在c#中调整图像大小
本文关键字:图像 调整 | 更新日期: 2023-09-27 18:12:50
我在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();
}