Resizing image in C#

bitmap, c#, resize

Solution

Instead of copying the bitmaps in two steps, make it one step. That way you reduce the memory usage quite a bit as you don't have two copies of the oringal image in memory at once.

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();
}

Problem

I am writing a code to resize JPG images in C#. My code takes around 6 seconds to resize 20 JPG images. I am wondering if there is any faster way of doing this in C#? Any suggestion to improve this is appreciated! Here is my code now: ``` 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(); } ``` Thanks to @Guffa for his solution. I moved the dispose() out of foreach loop. The updated and fast code is: ``` 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(); ```

Original source