<< Back To All Blogs
Creating High Quality Images with C# and GDI
Thursday, August 13th, 2009
I have posted in the past about creating organizational charts using C# and GDI, but I have recently come across a scenario in which I needed to make the charts show up as 100% quality (they were blurred because of the default, lower-quality GDI output).
Low and behold GDI does indeed support the ability to change output quality to a Bitmap, and while it isn't the easiest thing to figure out originally, it really isn't that bad.
So I figure the best way is to jump right into the code, so here we go. All of these classes are available in the System.Drawing.Imaging namespace of .NET:
// Encoder parameters can hold multiple parameters to pass to the Save method for the Bitmap class
EncoderParameters encoderParams = new EncoderParameters();
// Requires an array for the quality parameter
long quality = new long;
// 100 is 100%, 0 is 0%
quality = 100;
// Create a new encoder parameter with the specified quality array from above
EncoderParameter qualityParam = new EncoderParameter(Encoder.Quality, quality);
// Add this parameter to the entire collection
encoderParams.Param = qualityParam;
// This could either be a newly-created Bitmap, or come from a loaded image, etc
Bitmap result = GetBitmapOutput();
// We can no longer pass the normal ImageFormat Enum to the Save method, so we need to find the actual encoder from C#/GDI
ImageCodecInfo ici = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo encoder = null;
// Loop through them all and set the encoder if we find it to be on JPEG, this could also be used for PNG, GIF, etc
for (int a = 0; a < ici.Length; a++)
encoder = ici[a];
// Save the Bitmap to the output stream (in my case), with the specified encoder and encoder parameters
result.Save(Response.OutputStream, encoder, encoderParams);
// Clean up
Not too bad, hopefully that will help some of you along the way.
Imagin' Tom Out.
Calling .NET WebService From PHP
Creating a reusable web client for PUT, POST, and DELETE in C#
Reading a Microsoft Project file (mpp) in C#
Programatically Retrieving an Assembly's PublicKeyToken through a PowerShell CmdLet
Reading an XML file using LINQ
Currently no comments.
Add A Comment
Email Address: (not public, used to send notifications on further comments)
Enter the text above, except for the 1st and last character: