.NET Image Resizing Console Application
I just finished creating a small .image manipulating NET console application that has several primary capabilities:
- resize an image to a specified size (or percentage)
- rotate an image 90 degrees counter-clockwise
- reduce the quality
Nothing too revolutionary about the code. I'll mention a couple of the more interesting/useful pieces.
When saving an Image to a file via the Image.Save method, a codec is needed if you need to do anything custom. In my code, I needed to optionally reduce the quality of the image to a user specified value (the /Q:## option). For some reason Microsoft made retrieving a particular codec an effort left up to the developer rather than wrapping it in a handy static method.
private static ImageCodecInfo GetEncoder(string mimeType)
{
ImageCodecInfo[] encoders =
ImageCodecInfo.GetImageDecoders();
for (int i = 0; i < encoders.Length; ++i) {
if (encoders[i].MimeType == mimeType) {
return encoders[i];
}
}
return null;
}
To retrieve the JPEG encoder:
ImageCodecInfo codec = GetEncoder("image/jpeg");To set the quality parameter for the JPEG encoder:
EncoderParameters parameters = new EncoderParameters(1);
parameters.Param[0] =
new EncoderParameter(Encoder.Quality,
(long) quality);reducedImage.Save(destinationFile, codec, parameters);
To reduce the image to the user specified value (the /W:##, /H:##, or the /S:## options), the application takes the original image and draws it to a smaller image at the best quality (using the InteroplationMode):
using (Image reducedImage =
new Bitmap(scaleWidth,
scaleHeight,
image.PixelFormat))
{
using (Graphics g = Graphics.FromImage(reducedImage)) {
g.InterpolationMode =
InterpolationMode.HighQualityBicubic ;
g.DrawImage(image, resizedRect);
}
... continues ...
The remainder of the code is house keeping, dealing with handling the various command line parameters and displaying help text. By default, the application creates the modified version of the image in a "Modified" subfolder (a subfolder of the original image's folder). To overwrite the image, use the /O option. The application displays the help text if no command line parameters are provided.
I haven't tested the application extensively. Use at your own risk.
The full code and executable is here: resize.zip.