简体   繁体   中英

Resizing image in C#

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM