调整C#中的图像大小

时间:2014-07-15 00:41:05

标签: c# bitmap resize

我正在编写一个代码来调整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();

1 个答案:

答案 0 :(得分:5)

不要分两步复制位图,而是一步到位。这样你可以减少内存使用量,因为你不能同时在内存中有两个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();
}
相关问题