Given the code where resizedImage
is of the type System.Drawing.Image
:
using (var resizedImage = Resizer.ResizeImage(bytes, requestedWidth))
{
return PNGCompressor.LosslesslyCompressPNG(resizedImage);
}
And the method is defined as:
public static byte[] LosslesslyCompressPNG(Image image)
{
var fileName = Guid.NewGuid();
var inputFilePath = TempCompressionFolder + fileName + ".png";
image.Save(inputFilePath, ImageFormat.Png);
var outputFilePath = TempCompressionFolder + fileName + "_comp.png";
var startInfo = new ProcessStartInfo
{
FileName = PathToOptiPNGExe,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
Arguments = "\"" + inputFilePath + "\" -out \"" + outputFilePath + "\" -o2 -strip all"
};
using (var process = Process.Start(startInfo))
{
if (process == null)
{
throw new Exception("Could not start " + PathToOptiPNGExe);
}
process.WaitForExit(Settings.Executables.WaitForExitMS);
if (!process.HasExited)
{
process.Kill();
}
}
var bytes = File.ReadAllBytes(outputFilePath);
File.Delete(outputFilePath);
File.Delete(inputFilePath);
return bytes;
}
Will resizedImage
always be disposed? I'm wondering if this is a source of a memory leak or not due to the new process being started.
using
statement guarantee that Dispose
will be called even in the case of an exception.
The fact that you are starting new process won't do anything with this instance because you are not using the instance with this new process only string
parameter. Even if you were using this instance (through stream parameter or whatever), the using
statement will take care of disposing and releasing the instance.
By the way, what I understand is that you are using optipng tool only to "strip" metadata. There is many other way of doing it without involving creating a file on disk and starting a new process. See easy way to clean metadata from an image for example