Resizing an image in C #

I am writing code to change jpg images in C #. My code takes about 6 seconds to resize 20 jpg images. I am wondering if there is a faster way to do this in C #? Any suggestions for improving this are 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 @Guffa for his solution. I moved dispose () from the foreach loop. Updated and fast code:

        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();
+4
source share
1 answer

Instead of copying bitmap images in two steps, do it in one step. Thus, you reduce memory usage a bit, since you do not have two copies of the original 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();
}
+4
source

Source: https://habr.com/ru/post/1548422/


All Articles