Lossless Image Resizing in C# - Getting Started
(Page 3 of 6 )
The DLL we will need is called the BetterImageProcessQuantization.dll - download the archive and extract this dynamic link library file into your Lightweight Image Manipulation project that we created in the previous article. I've also included it in the source code project archive, which you'll find attached at the end of this tutorial.
Once we've done this, we need to append the following line in order to use its namespace:
using BetterImageProcessorQuantization;
After this stage, we need to change only the GIF case part in our saveFile method. If you still remember, that was our method that saved the converted file. Check out the following code of our method and change it where it's required (case "GIF" at switch!):
private void saveFile(Image img, string NewFileName, string NewFileExtension)
{
EncoderParameters codecParams = new EncoderParameters(1);
codecParams.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
ImageCodecInfo[] encoders;
encoders = ImageCodecInfo.GetImageEncoders();
bool success; success = false;
try
{
switch (NewFileExtension.ToUpper())
{
case "PNG": img.Save(NewFileName, encoders[4], codecParams); success = true;
break;
case "BMP": img.Save(NewFileName, encoders[0], codecParams); success = true;
break;
case "JPG": img.Save(NewFileName, encoders[1], codecParams); success = true;
break;
case "GIF": OctreeQuantizer quantizer = new OctreeQuantizer(255, 8);
using (Image quantized = quantizer.Quantize(img))
{
quantized.Save(NewFileName, encoders[2], codecParams);
}
success = true; break;
}
}
catch
{
MessageBox.Show("Failed to save image to " + NewFileName, "Error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (success == true)
MessageBox.Show("Image file saved to " + NewFileName, "Image Saved",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
I'm sure you already noticed that I have added the "bold" effect to the changes that you should apply to the "GIF" block of code. That's where our new quantization algorithm comes in handy (developed by Wesley Bakker). Basically, the algorithm works like this: it sets the quantizer to 255 colors and 8 bits. After this, it quantizes our source image appropriately and then saves our already quantized image. Simply put, the image already contains less than 256-colors, so GDI+ won't re-quantize.
That's all for this section. For more information, check out the online documentation of Better Image Processor located at Wesley Bakker's website. Regardless, please don't have sky-high expectations of this algorithm, since there's no "perfect" quantization algorithm that would work ideally for every image.
Next: Let's Resize! >>
More C# Articles
More By Barzan "Tony" Antal