I have a simple C# application for renaming and resizing images, and I have a little problem - when it completes working with all given files, the last one always stays in the memory, or whatever, of the program, and I can't delete it without closing the program.
How can I make my code always release the files it works with after it has finished?
here's what I have
private void processFiles() {
foreach (string oldFileNamePath in fileEntries) {
...
File.Move(oldFileNamePath, newFileNamePath);
if (isResizeImage) {
if (!extension.Equals(".gif")) {
Image newImage = Image.FromFile(newFileNamePath);
int newWidth = (int) (newImage.Width * (1 + ((double) percentageSize / 100)));
int newHeight = (int) (newImage.Height * (1 + ((double) percentageSize / 100)));
newImage = ResizeImage(newFileNamePath, newWidth, newHeight);
newImage.Save(directory + RESIZED_DIRECTORY + "\\" + newFileName, ImageFormat.Jpeg);
newImage.Dispose();
} else {
// only move
File.Move(newFileNamePath, directory + RESIZED_DIRECTORY + "\\" + newFileName);
}
}
}
}
public static Bitmap ResizeImage(String path, int width, int height) {
Image image = Image.FromFile(path);
var destRect = new Rectangle(0, 0, width, height);
var destImage = new Bitmap(width, height);
destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (var graphics = Graphics.FromImage(destImage)) {
// process image
using (var wrapMode = new ImageAttributes()) {
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
}
image.Dispose();
return destImage;
}
}
The original newImage isn't exposed. You are reassigning it and disposing the new imageNew you are receiving from ResizeImage.
Remove the following:
And move your declaration to the next line. This line didn't do anything, since you replace it immediately after and dispose the new replacement, but never the original.
After edit of OP:
You should do this:
For explanation purposes I did leave out the use of using. But normally you should do that: