CodeGuru
Earthweb Search
Forums Wireless Jars Gamelan Developer.com
CodeGuru Navigation
Member Sign In
User ID:
Password:
Remember Me:
Forgot Password?
Not a member?
Click here for more information and to register.

Search
The Business Internet

jobs.internet.com

internet.commerce
Partners & Affiliates
KVM Switches
Shop
Boat Donations
Imprinted Gifts
Best Price
Televisions
Server Racks
Web Hosting Directory
Laptops
Compare Prices
KVM Switch over IP
Computer Deals
GPS
Remote Online Backup


RSS Feeds

RSSAll

RSSVC++/C++

RSS.NET/C#

RSSVB

See more EarthWeb Network feeds

Home >> Visual C++ / C++ >> Graphics & Multimedia >> GDI >> GDI+

Project Management Guide: Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.

Better GIFs with Octrees
Rating:

Sjaak Priester (view profile)
February 6, 2004


(continued)



 Silverlight 2 SDK for Visual Studio 2008
This package is an add-on to the RTM release of Visual Studio 2008 to provide tooling for Microsoft Silverlight 2 Beta 1. It provides a Silverlight project system for developing Silverlight applications using C# or Visual Basic. »
 
 Article: What Does it Take to Build the Best RIA?
With the proliferation of Rich Interactive Application (RIA) platform choices out there, you no longer have to take a one-size-fits-all approach to developing your next RIA application. Knowing the strengths (and weaknesses) of each platform can help you to decide the best RIA for your next application. »
 
 Expression Blend 2.5 Preview
Use Expression Blend 2.5 to create and modify managed Silverlight 2-based applications. Expression Blend for Silverlight 2 includes all of the features in Expression Blend 2 but has not reached the quality level of Expression Blend 2 for WPF or Silverlight 1 development. »
 
 The Hottest Mobile Platform Meets the Hottest RIA Platform
With the Symbian OS now supporting Microsoft Silverlight, mobile developers can bring new and exciting capabilities to handsets all over the globe. Find out why developers now need to make mobile devices a core part of their RIA development strategy. »
 
 Article: Leveraging Your Flash Development with Silverlight
You're not giving up Flash any time soon (and we don't blame you.) But if you could get your Flash application working in Silverlight, why wouldn't you? We show you the tools and techniques required to have your rockin' Flash application rolled for Silverlight. »
 

Environment: VC++ 6.0/7.0, Windows 98 and later, GDI+.

Original JPG picture Default GIF picture GIF picture after octree color quantization

QColorQuantizer Gets the Most out of Your Picture

GDI+, the new graphics API that was introduced with Windows XP, lets you save GIF files quite easily. That's a good thing, of course. However, the default GIF files GDI+ produces are not the most perfect ones. With a bit of extra work, we can do better.

Look at my portrait above. Left is the original bitmap picture in JPG format. The second picture shows how GDI+ transforms it to GIF format. At the right is another GIF picture, but this time the bitmap has been put through octree color quantization.

The problem

As most of you will know, GIF files contain only 256 colors at the most, far fewer than the average picture. What's needed is a way to find 256 or fewer colors that can be used to represent the original colors as genuinely as possible. These colors will fill the palette of the GIF file. This process is called 'color quantization.'

When GDI+ saves a bitmap in GIF format, it performs a very crude form of color quantization. It always uses the same color palette, mostly filled with the 216 'Web-safe colors.' In the early years of the Internet, these colors were the only ones to be displayed consistently by most browsers; hence the name. However, a fixed set of colors will almost never be the optimum palette for any given picture. On top of that, the 216 Web-safe colors were chosen purely on the basis of their technical merits (they uniformly divide the RGB color space), and not because of their visual qualities. As a consequence, the Web-safe palette (also called the 'halftone palette') contains many almost indiscernible purples and a lot of muddy greenish and brownish colors, whereas some more useable parts of the spectrum are seriously underpopulated.

Because it always uses a fixed palette, GDI+ doesn't even save bitmaps with fewer than 256 colors correctly in GIF format. Every color is changed into one of the Web-safe colors, deteriorating the picture.

Adaptive color quantization

Far better is 'adaptive' or 'optimized' color quantization. This helps in both cases. Bitmaps with 256 or fewer colors are saved as perfect GIFs. And it's remarkable to see that a photographic picture with the right color palette often displays almost as well as GDI+'s native 24 bits bitmap, with its 16,777,216 colors.

Adaptive color quantization is no trivial task, however. Quite a few algorithms have been invented, varying from complicated to very complicated. Color quantization is still the subject of intensive research; it is also important for computer vision and related areas.

For this project, I chose a very elegant method with the impressive name of the 'Gervautz-Purgathofer octree algorithm.' Michael Gervautz and Werner Purgathofer invented it, fifteen years ago, at the Technische Universität Wien in Austria. The 'octree' is the data structure that plays a key role in the algorithm.

I also investigated another algorithm, called the 'Heckbert median cut.' This yields different results which, according to some, are superior to those of the octree method. I found the difference to be extremely small, however, while 'median cut' was up to eight times slower, mainly because data often has to be sorted.

So, octree it is. The algorithm first collects all the colors used in the bitmap. Each new color is put in a tree structure. The big trick is that the tree structure is not allowed to grow more than 256 'leaves' (ending nodes). As soon as this is imminent, the tree is pruned. A number of leaves representing relatively few pixels with closely related colors are replaced with one leaf. Because the tree never grows beyond 256 leaves, there is never much data to handle. Therefore, the algorithm is quite efficient.

The tree structure used is the octree, in effect a three-dimensional tree in RGB color space. Every node can have up to eight child nodes. The leaves are points in the color space, and the higher nodes define paths to the leaves. The bits of the RGB color value are used to navigate in the octree. The highest bits of R, G, and B determine the first branch from the root, the next highest bits the second step, and so on. It's all very clever.

After all the color information is condensed in the octree, a color palette is created by iterating through the octree leaves. Notice that it may contain fewer than 256 colors, even if the source bitmap is very rich in color. Finally, the bitmap is scanned again. The 24-bit color information is replaced by an 8-bit index in the palette.

QColorQuantizer

I encapsulated my version of the octree in a single MFC class, QColorQuantizer. Using it is extremely simple. Just call one function:

  Bitmap * GetQuantized(Image * pSource, Mode mode);

The parameter pSource is a pointer to a bitmap of any GDI+ format. If all goes well, the function returns a pointer to a new color quantized bitmap of the same size, ready to be saved as a GIF file. If mode has the value WebSafe, the returned bitmap sports the rigid, Web-safe color palette. If mode has the value Octree, octree color quantization has been performed. If anything goes wrong (presumably because of a lack of memory), GetQuantized() returns NULL.

Because octree color quantization is a somewhat lengthy operation, there is an option to perform it in a separate worker thread. To do so, call the function:

  void MakeQuantized(Image * pSource, Mode mode, CWnd * pMsgWnd);

The parameters pSource and mode are identical to those of GetQuantized(). This function, however, returns immediately. When the quantization algorithm is finished, the window pointed to by pMsgWnd receives the special Windows message QM_COLORQUANTIZER. The LPARAM parameter of this message contains a pointer to a new quantized bitmap, or NULL in case of failure (the WPARAM parameter is not used).

In both cases, the calling function or the receiving window gets the ownership of the quantized bitmap and is responsible for deleting it. Actually, both functions have a few extra default parameters. See the source for details.

Tinter 1.3

I incorporated QColorQuantizer in the latest version of Tinter, my work in progress with a plethora of bitmap tools. The first version demonstrated color matrices. Version 1.1 added sharpening and blurring tools. Version 1.2 had zooming capabilities and scanning support, and displayed image properties. This latest version has a new 'GIF Preview' command in the 'View' menu, and an option to create Web-safe or octree GIF files. In the preview window, you can switch between the two modes to study the difference. I didn't use a worker thread for color quantization. As an extra, I also added a command to change the size of the bitmap.

References

Note: for this project, your system must support GDI+, which currently only XP does natively. However, other Windows versions can be upgraded. Also, VC++ 6.0 comes without the GDI+ headers. You may obtain them by downloading the Windows Platform SDK. The GDI+ headers are included with VC++ 7.0.

Downloads

Download demo project and source - 191 Kb
Download demo project executable only - 62 Kb

Tools:
Add www.codeguru.com to your favorites
Add www.codeguru.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed

Whitepaper: Enterprise Information Integration--Deployment Best Practices for Low-Cost Implementation
Developing Intelligent Communications? Visit the Avaya DevConnect Center on DevX.
Guide to Developing a Web Site. Best Practices, Tips and Strategies. Download Exclusive eBook Now.
Five Trends for Application Development. Download Your Complimentary Report. Exclusive. Act Now.
Learn about expanding business opportunities for the reseller channel. Visit IT Channel Planet.


RATE THIS ARTICLE:   Excellent  Very Good  Average  Below Average  Poor  

(You must be signed in to rank an article. Not a member? Click here to register)

Latest Comments:
http://www.ucancode.net - Legacy CodeGuru (02/23/2004)

View All Comments
Add a Comment:
Title:
Comment:
Pre-Formatted: Check this if you want the text to display with the formatting as typed (good for source code)



(You must be signed in to comment on an article. Not a member? Click here to register)


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: Will Hyper-V Make VMware This Decade's Netscape?
Microsoft Article: 7.0, Microsoft's Lucky Version?
Microsoft Article: Hyper-V--The Killer Feature in Windows Server 2008
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Windows Server 2008
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES