This is the second segment of the two-part article series focusing on the creation of a lightweight image manipulation application that is able to perform lossless image conversion and resizing. The programming language is C# and we rely on .NET’s GDI+ and graphics because our project is designed in Visual Studio.
In case you missed the first part, I strongly suggest that you stop for a moment and take your time to read it (also here on ASP Free), comprehend it, and develop and create the required first application that does the image conversion, because in this part we are going to work on that ready-to-run application by extending it.
As I mentioned in the first segment, throughout this tutorial I will assume that the reader has syntax familiarity and at least intermediate programming experience with the C# language and hopefully .NET. We will maintain our pace the way we advanced in the first part - a relatively fast speed, but I am going to attach all the code snippets required for subroutines, methods, and so forth.
I'm sure that following along won't be a hard task, especially if you paid attention to the first part. However, even if you have read it, I suggest that you skim through that article again and launch your copy of Visual Studio to recheck your code. It always helps to refresh our memories. Once you feel prepared, we can begin.
As I've promised, at the end of this tutorial you will find the entire project archived and accompanied with the fully commented and organized source code of the Lightweight Image Manipulation application that we've developed during this two-part series. Have fun and I truly hope that you will find it useful and straightforward. Enjoy!
Let's remind ourselves of the way we defined quantization and why it is necessary for GIF conversions. First, we all know that JPEG images are full-colored and that the format is able to store 24 bit images with the appropriate palettes. This means that when you want to display a 24-bit or higher bit JPEG image on 8-bit hardware, for example, the image viewer application quantizes the colors to 8 bit.
Thus, the display process becomes drastically slow - of course, this depends on the hardware of the system as well as the algorithm that's used by the image viewer. In a nutshell, color quantization stands for color reduction, so it matches the hardware capabilities and therefore the system is able to display the images.
Needless to say, we are living in a generation where having 24-bit colors is "the norm," so this isn't an issue with JPEG and other formats. Fortunately, by their very nature, as I explained before, they can support up to 24-bit and more colors. That's why our JPEG, PNG, BMP, etc. images are so razor sharp and high quality.
But the scenario is different in the case of GIFs. The GIF format was designed with weak system performance in mind, especially 8-bit or less color display possibilities. Due to this, by definition the GIF image format doesn't allow more than 256 color palette entries; each palette contains a specific number of colors. This means that an image saved/converted to the GIF format cannot contain more than 8-bit colors.
You see, the aforementioned fact explains why color quantization is a must when we convert higher than 8-bit colored images to the GIF format. The GDI+ of the .NET environment is optimized for speed and because of this, it sort of neglects image quality. Thus, the default quantization algorithm incorporated by Microsoft, unfortunately, produces pixelated and low quality images.
The quantization algorithm is very dependent upon the source image. Sometimes is looks quite acceptable, other times the image becomes almost totally destroyed due to hundreds of misplaced and wrongly colored pixels, resulting in all-around pixelation.
In the first part of this series, I attached a comparison picture where an original 24-bit JPEG image is compared to an 8-bit quantized image done with the GDI+ standard algorithm. It turned out quite awful. Here we show another example. The results are "acceptable," but the loss is clearly visible.
(The left photo is 24-bit original JPEG while the right one is the quantized 8-bit GIF.)
In a nutshell, quantization is necessary each time we work with GIFs because by the format's very nature it cannot accept more than 256 colors. Therefore, we need to design a quantization algorithm which reduces the original source image's bit-depth to 8-bit. Developing a high-quality color quantization algorithm from scratch is a black art and a very complicated process. Add to this the fact that there does not exist an algorithm that is optimal for every possible image. It is impossible.
As we've presented here, it is clear enough that in this era of computing GIFs are quite obsolete. That's why nowadays you don't really come across the GIF format, excluding the cases when the GIF in question is animated. Animations of 8-bit or less are acceptable, since their size grows linearly to the number of frames anyway.
Notwithstanding, we don't want to leave this part unresolved in our application, so we brainstorm for a solution. Searching Google for "good color quantization algorithm" is a way to find answers. I have come across Wesley Bakker's Better Image Processor [BIP] project that is freely distributed in its DLL form at his site. You can download the whole BIP in its entirety containing 3 DLLs, but we are only going to need one of them.
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!):
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.
We have finally covered the quantization process and we can theoretically perform lossless conversion and save images, excluding the GIF limitations. We cannot violate the nature of GIFs or spend countless hours developing ourselves a better quantization algorithm - GIFs are obsolete anyway, so let's get over it! Now it's time to architect and implement the resizing function into our application.
First of all, as you'd expect, we are going to add new components to our form. I for one have added the following new components: another button called btnResize, two textboxes called txtHeight and txtWidth, a few additional labels such as lbResize, lblRatio, lbl_x (check the screenshot attached below to understand), and of course, another piece of saveFileDialog2, which is required when we want to save our destination file.
As I mentioned, check out the screenshot below - it should definitely help you.
(Form Design - Screenshot)
The rest remained untouched, such as picThumbnail, btnQuit, btnSelectPicture, btnConvert, and of course the form remained clsMain. All that is left to modify is to Show and Hide the appropriate labels and buttons when needed. This means that before we load a picture, we hide all of the components excluding two buttons (Quit and Select Picture) and the picThumbnail. After we've chosen the source image, voila, the rest of the components also appear. Now we'll have a powerful application.
I won't attach code snippets for the additions I described above because it's quite self-explanatory and it was explained thoroughly during the first part of this series. And even if you cannot do this, the components will always be visible - it simply doesn't look professional enough. We can afford that kind of possibility.
Now let's write the resizing algorithms! We need to code the btnResize_Click and saveFileDialog2_FileOK methods. However, we are going to create another method as well as a new function. These are going to act as the foundation for our resizing action. These are ResizeImage() and GetDimensions. The first handles the resizing process while the latter calculates the new dimensions, because we maintain proportionality (ratio).
public void ResizeImage(int MaxWidth, int MaxHeight, string FileName, string NewFileName, string NewFileExtension)
Bitmap NewImg = new Bitmap(OrigImg, ResizedDimensions);
saveFile(NewImg, NewFileName, NewFileExtension);
}
The above code snippet is our ResizeImage method. It clones the source image and then calls our next-to-be-written GetDimensions function to calculate the new, resized dimensions. After these we can finally call our saveFile method, which remained untouched since the quantization changes (previous page). So let's see GetDimensions!
public static Size GetDimensions(int MaxWidth, int MaxHeight, ref Bitmap Img)
Maybe it isn't as straightforward as I had hoped. Anyway, I'm going to explain how it works. Basically, we want to preserve proportionality (ratio). At first, we check whether the new sizes aren't smaller than the original ones (in this case, we return the original ones and basically do zero resizing). If this isn't the case, then we calculate the MaxWidth and Width ratio - basically MaxWidth stands for the explicitly specified width.
After this, we're able to see whether we need to fiddle with the height of the image. In that case, we resize it using the multiplier we've just calculated to maintain the proportionality. Of course, after this we also need to reduce the size of the width, so we calculate the MaxHeight and Height ratio to accomplish this. Once all of this is done, we end this function by returning our new size.
Now that we've finished writing our method and function, we can complete our project by adding the code snippets to the appropriate components to develop those parts which will execute when we click on btnResize and saveFileDialog2's OK button after choosing the destination location. Check 'em out!
saveFileDialog2.Filter = "Joint Photographic Experts Group Format (*.jpg)|*.jpg|" + "Graphics Interchange Format (*.gif)|*.gif|" + "Bitmap Format (*.bmp)|*.bmp|" + "Portable Network Graphics Format (*.png)|*.png";
You see? After completing these blocks of code, we have finished our Lightweight Image Manipulation application. Now just head over to the next page because that's the location to download the archived source code of this entire project. You will also l find some of my closing thoughts and final words regarding this tutorial.
We've done it! Yes, you are allowed to cheer enthusiastically. I'm pretty sure that if you haven't had any particular experience working with images in C#, then this project was more than interesting. Let's admit it... it's much more fun to write code that handles and manages images, because we can visually see the results. How's that compared to building code based on low level bit operators or perhaps dynamic memory allocation?
Because keeping promises is part of our ethics and that's the deontological way of doing it, the Download Source button below is hyperlinked to the source2.zip archive. Keep in mind that I've developed it using Visual Studio 2005, but it should work with any other Visual Studio IDE. Just extract it and have fun with it... enjoy!
We cannot finish this tutorial without including a screenshot of our "final product."
(Lightweight Image Manipulation in action)
For any other software development questions and issues don't hesitate to join the community at DevHardware Forums - despite its name, we specialize in both hardware and software including consumer electronics. Furthermore, you might as well join and test the knowledge of our sister-site communities, such as ASP Free Forums and DevShed Forums.
All of this being said it's time for us to say good-bye... at least for now. Don't ever forget that perfect practice makes practice. Follow that guideline and keep on codin'!