Click here to Skip to main content
13,347,168 members (55,342 online)
Click here to Skip to main content
Add your own
alternative version


157 bookmarked
Posted 17 Sep 2001

Drawing transparent bitmaps using CImage

, 17 Sep 2001
Rate this:
Please Sign up or sign in to vote.
Universal implementation of transparent drawing of bitmap files (BMP, JPEG, GIF, PNG). Based on the method described by Chris Becke and Raja Segar.

Transparent GIF


The article Drawing Transparent Bitmap with ease with on the fly masks in MFC demonstrates how to draw a CBitmap transparently. The article doesn't include a demo project. Here you'll find a complete implementation including a demo project. This implementation brings the transparency technique into a larger context than CBitmap, as it's able to read and draw several file formats, including file formats with built-in transparency (PNG and GIF).


There are many bits and pieces on painting and manipulating bitmaps in this Code Project section, but we are in dire need of a complete DIB class. (ed. For a DIBSection class, see A DIBSection wrapper for Win32 and WinCE) Windows doesn't help out much. The bitmap API is rudimentary. If you only want to paint bitmaps of various formats, IPicture/OleLoadPicturePath looks like it. Only it doesn't support PNG! Nor animated GIF. Obviously Internet Explorer doesn't use this API. Perhaps they're using CImage! CImage was created back in 1996 by Julian Smart, who adopted code from Alejandro Aguilar Sierra. Julian Smarts implementation uses MFC for no apparant reason (so we all do from time to time), and is somewhat cluttered, but a great first step on the way. He seems to have lost interest in the project on July 18th 1998, since when it wasn't maintained. Recently Davide Pizzolato adopted the class, renaming it CxImage. He added several file formats and fixed up the code but did nothing about the structure of the code. Most of the clutter of 1998 is still there, and then some. I've undertaken to fix up the CImage/CxImage code as well as adding value, especially transparent painting of bitmaps. How were we supposed to do without? To some readers the decoupling of the CImage class from MFC might be of interest, as it makes it a breeze to take CImage to compilers other than Microsoft Visual C++. This is in accordance with the image reader libraries (JPEG, TIFF, PNG) on which this is based. They're totally cross-platform. For the MFC programmers I'm providing a derived class, CImageObject. It's a neat MFC wrapper around CImage.

Please consider this contribution one step towards making production code out of CImage.

Code highlights:

// cimage.h

// The base class CImageBase is a simple interface class, just a vtable 
// holder really. Gives you an idea of what behavior you might want to change 
// in a derived class. DrawImplementation is the most interesting, as 
// different projects have different objectives (drawing speed over 
// capabilities or vice versa etc.)

class CImageBase
   virtual BOOL DrawImplementation(HDC hdc, int xDst, int yDst...

// The derived class, CImage, know about Windows DIB handling. 
// It also reads and writes bitmaps from/to different file formats

class CImage : public CImageBase
   virtual BOOL DrawImplementation(HDC hdc...
   BOOL CreateFromFile(LPCSTR  filename, enum cximage_type);
   BOOL Save(LPCSTR  filename, enum cximage_type);

   virtual BOOL Read (FILE*, enum cximage_type);
   virtual BOOL Write(FILE*, enum cximage_type);

// Operations - special effects
   BOOL Flip();
   BOOL Mirror();
   BOOL Negative();
   BOOL GreyScale();
   BOOL Rotate(double angle);
   BOOL WalkColors(COLORREF(*manipulate)(BYTE r, BYTE g, BYTE b, LPVOID), 
                   LPVOID lpUser = NULL);

// imgobj.h

// The class CImageObject, brings CImage in line with MFC by deriving from 
// CObject and implementing Serialize

class CImageObject : public CImage, public CObject
   virtual void Serialize(CArchive&);
   virtual void Close(void);
   BOOL Read(CStdioFile*);
   BOOL Write(CStdioFile*);
   BOOL Draw(CDC*, int xDst = 0, int yDst = 0, int cxDst = -1, int cyDst = -1, 
                   int xSrc = 0, int ySrc = 0, int cxSrc = -1, int cySrc = -1);

// trans.c

// Implementation of DrawTransparentBitmap, used by CImage::DrawImplementation

EXTERN_C BOOL WINAPI DrawTransparentBitmap(HDC hdcDst, HDC hdcImage, 
                                           COLORREF crTransparent...

CImage structure

Many people are confused by the specialized classes derived from CImage, eg. CImageGIF. Actually these specialized classes are to be considered implementation details: The CImageGIF isn't really a GIF class, but merely an import/export class that knows about the specific graphics format's file layout. It's all one class, so to speak (CImage).

There's no GIF class proper. CImage converts all file formats into DIB. CImage is a Windows DIB class, it can hold only a Windows DIB image (and will not easily port to other platforms).

In the table below, you can observe how the library's implemented in layers, with the Demo application sitting on the top of it all. The Demo uses only class CImage and considers it a blackbox, and so can you.

Demo application - C++ code
CImage - C++ code MFC +
C Runtime Library
(C++ code)
(C++ code)
(C++ code)
(C++ code)
(C++ code)

(C++ code)
Windows API +
C Runtime Library
C Runtime LibraryPNG
(C code)
(C code)
(C code)
Windows API + C Runtime Library
(C code)
C Runtime LibraryC Runtime LibraryC Runtime Library

Notes on code quality:

  • I consider the ZLIB, JPEG, TIFF and PNG libraries production code.
  • The CImage class still have some way to go.
  • The Demo application as provided is a 'clean' MFC application, more so than the earlier attempts, and is now a fine boilerplate MFC application, I think.

CImage Project Settings

The actual library is project imagedll and imagelib, for DLL and lib builds. Only Debug and Release targets are needed. Unicode build is not needed, as there isn't much string handling left in CImage imagedll/lib contains all the actual bitmap code, including the jpeg, png and tiff code. zlib is kept out, as it isn't image code as such.

Remember to build (some of) these targets before attempting to build the Demo application, it needs to link with imagedll/lib.

Project Targets

Demo Project Settings

Here you see combinations of the _MBCS, _UNICODE and _IMAGEDLL compiler options. Pick and choose. (All are _AFXDLL.)

Demo Targets

Of interest

Author's points of view as exercised on CImage:

  • Don't implement it using MFC if it's just as easy to implement without
  • Don't implement it using STL if it's just as easy to implement using MFC
  • Don't implement it in C++ if it's just as easy to implement in C.
  • I like all of them (except STL)
  • Keep char usage on a minimum, make the code Unicode-compatible.
  • Keep it simple.


  • Clean up Copy/Transfer/Detach/Ghost/constructor mess
  • Implement reference counting a la CString
  • Will somebody provide a WTL Demo application?
  • DrawTransparentBitmap fails on the printer on 'large' images. Any suggestions?
  • The code generates loads of warnings, mostly because of BYTE variable. Should use int.

CImage history:

CImage 1.4.1: Added transparent draw. fopen/fclose clutter removed. Unicode enabled. Cleaned up the project workspace. Added Unicode and DLL targets. Removed remaining MFC dependencies.

CImage 1.4: Julian Smart supported JPEG, PNG, BMP and GIF - 256 colors only.

CxImage 1.1: Some support for multi-image files. Davide used some of my code and forgot leaving credits. In the Demo application, I contributed with printing support, CMemDC usage, hatched background, entire CDemoView::OnDraw. I also wrote CxImageGIF::Decode, adding (rudimentary) support of animated GIF.

CxImage 1.0: Davide Pizzolato added much value, including support for ICON and TIFF and true color. He removed most MFC dependencies, but didn't go all the way for some reason.

The MFC Demo application included with CImage and CxImage are coded in a way rather insensitive to MFC paradigms, ignoring printing, print preview and abusing CScrollView. The Demo application supplied here remedies that.

CImage change log:

Version 1.4.1 - Aug. 29th 2001 (Troels K.)
- Merged with CxImage 1.01
Changes in project file:
- Utilizing Project|Dependencies
- Proper output directory structure (LIB, Release\Unicode etc.)
Changes in CImage and derived classes:
- Implemented transparency on screen and printer (CImage::Draw)
- Unicode-enabled ("const char* filename" -> FILE* )
- MFC-style CreateFromFile/Close member functions (ReadFile/SaveFile)
- Removed silly MFC-dependency (#include afxwin.h)
- 'Bug' fix in TIFF: -> jconfig.h
- Created tif_c.c
- Bug fix in CImage::LoadResource (tmpfile never closed)
- Bug fix in CImagePNG::SaveFile (assert i delete [])
- Bug fix in CImageGIF::Open (bad pack)
- Bug fix in CImageGIF::SaveFile(ignored transparency)
- Added WalkColors/Greyscale method
- Enabled handling of animated gif's (CImageGIF::Open).
- Enabled reading of RLE-compressed bitmaps
- Bug fix: Rotate didn't handle transparency (CImage::Rotate)
- Bug fix: Memory corruption in CImage::CImage(HBITMAP)
- Bug fix: GDI resource leakage in CImage::CImage(HBITMAP)
Changes in Demo application:
- Now utilizing CMemDC+CScrollView+CPreviewView+CArchive
- Added Unicode build
- Added serializing (CImageObject)
- Added hatched background
- Reorganized resource bitmaps
- Gif resource bitmap transparent to demonstrate transparent draw

Version - Aug. 22th 2001 (Troels K.)
- Merged with CxImage 1.0

Version 1.4 - July 18th 1998 (Julian Smart):
Fixed code creating a CBitmap from a CImage again...
Fixed MakeBitmap (Brett Levine).
Fixed memory leak in imajpg.cpp; added PNG 1.0.1 updates. Fixes by Konstantin Mihailov.
Fixed problem saving JPEG files, from Lars Bullwinkel.

Version 1.3 - June 28th 1997 (Julian Smart):
Fixed code creating a CBitmap from a CImage (I hope).
Added contributed GIF writing code from Randy Spann.

Version 1.2 - January 18th 1997 (Julian Smart):
Fixed code creating a CImage from a CBitmap, and added test to demo (under File menu).

Version 1.1 - January 9th 1997 (Julian Smart):
Fixed a problem with compiling the JPEG library (defining FAR) and changed the library directories to Debug and Release, instead of lib.

Version 1.0 - December 23rd 1996 (Julian Smart):
First release, based on the wxWindows wxImage class and many other bits and pieces.

CImage Q&A:

Q: How do I create transparent bitmaps?
A: Save the file in formats PNG or GIF, using Paint Shop Pro or the like

Q: I don't want to use either format, Unisys owns GIF and PNG is too esoteric for me, what to do?
A: Save as regular Windows BMP, and in your application, set the transparent color of your choice using CImage::SetBkColor. (It only works for palette bitmaps.)

Q: ...but I'm not ready for CImage. I want to use IPicture.
A: Then use IPicture, and bring in only trans.c. It's universal.


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

No Biography provided

You may also be interested in...


Comments and Discussions

QuestionProgram is crashing Pin
Member 111823795-Nov-14 19:04
memberMember 111823795-Nov-14 19:04 
Questionerror C2440: 'static_cast' : cannot convert from 'UINT (__thiscall CSettingsDlg::* )(CPoint)' to 'LRESULT (__thiscall CWnd::* )(CPoint)' 1> Cast from base to derived requires dynamic_cast or static_cast Pin
Member 111823795-Nov-14 18:38
memberMember 111823795-Nov-14 18:38 
QuestionBlack Backlground on Printing Pin
Rajeev Raina30-Sep-14 0:41
memberRajeev Raina30-Sep-14 0:41 
Questionhow to disable LNK4049 error warning? Pin
nenfa20-Apr-10 4:21
membernenfa20-Apr-10 4:21 
Generalcannot open file "..\lib\imagedll_d.lib" Pin
Ramz862-Nov-08 20:52
memberRamz862-Nov-08 20:52 
General..\lib\imagedll_d.lib is not found!!! Pin
ganesa moorthy2-Apr-08 1:07
memberganesa moorthy2-Apr-08 1:07 
Questionconversion from CImage to DIB Pin
Ralf0013-Jul-07 7:18
memberRalf0013-Jul-07 7:18 

How can I convert the content of a CImage to an device intependent bitmap (DIB)?
If i use the CImage method MakeBitmap(), it does not return a valid handler hDIB (see example).

The hDIB handle is stored in the DIB object where the following code executes:

if (!pDIB) return FALSE;

m_hDIB has a value other than NULL but GlobalLock() fails and pDIB is assigned to NULL!

The CIMage obj seems to be completely constructed - Why does MakeBitmap() not work?:
HBITMAP hBmp = (HBITMAP)bmp2.GetSafeHandle();
if (hBmp == NULL) return FALSE;

CImage ImageObj(hBmp);

hDIB = ImageObj.MakeBitmap(); // make DIB

// make as CDIBUse::ConvertToBMP() --> CBitmap !!!!!


Thanks for any hint or answer!
Generalcximage.lib(ximatran.obj) : error LNK2001: unresolved external symbol __imp__div Pin
denishernandez7-Feb-06 16:50
memberdenishernandez7-Feb-06 16:50 
GeneralAnother way to make a PNG file semi transparent Pin
JockeP17-Oct-05 7:43
memberJockeP17-Oct-05 7:43 
QuestionCan I use IPicture class and work on pixels? Pin
Joseph Abraham28-Sep-05 2:29
memberJoseph Abraham28-Sep-05 2:29 
Questionhow to save the image Pin
ashwinders14-Jun-05 1:01
memberashwinders14-Jun-05 1:01 
GeneralSystem Error Pin
extus11-Oct-04 1:21
memberextus11-Oct-04 1:21 
GeneralCImage into Drag&Drop Control Pin
Len20208-Apr-04 6:11
memberLen20208-Apr-04 6:11 
GeneralHOWTO: creating a text TRANSPARENT gif Pin
emmatty16-Feb-04 1:33
memberemmatty16-Feb-04 1:33 
QuestionWhere are swis.h and kernel.h? Pin
lewis.lewis17-Dec-03 9:30
memberlewis.lewis17-Dec-03 9:30 
QuestionHi,Does someone know Image Morpher ? Pin
xwshallwe@hotmail.com23-Sep-03 21:23
memberxwshallwe@hotmail.com23-Sep-03 21:23 
GeneralMissing File. Pin
WREY12-Jul-03 10:34
memberWREY12-Jul-03 10:34 
GeneralRe: Missing File. Pin
TRK14-Nov-03 2:26
memberTRK14-Nov-03 2:26 
Questionhow can I save a transparent gif file? Pin
graduate1820-Jun-03 20:37
sussgraduate1820-Jun-03 20:37 
GeneralSolved problem en DEBUG mode (LNK2005 errors) Pin
chris10910-Jun-03 22:52
memberchris10910-Jun-03 22:52 
GeneralSetting a skin using PNG from Resource using GDI+ in VC++ 6.0 Pin
AnthonyDass27-Apr-03 5:30
memberAnthonyDass27-Apr-03 5:30 
GeneralSerialize bug using CImageObject Pin
Ben Mathews18-Mar-03 9:31
memberBen Mathews18-Mar-03 9:31 
GeneralMFC 7 CImage Pin
Art Friesz20-Feb-03 15:05
memberArt Friesz20-Feb-03 15:05 
GeneralRe: MFC 7 CImage Pin
Christian Graus20-Feb-03 16:02
memberChristian Graus20-Feb-03 16:02 
GeneralTransparent PNG Pin
Tili16-Feb-03 17:08
memberTili16-Feb-03 17:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.180111.1 | Last Updated 18 Sep 2001
Article Copyright 2001 by Troels Knakkergaard
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid