Click here to Skip to main content
Click here to Skip to main content

Drawing transparent bitmaps using CImage

By , 17 Sep 2001
Rate this:
Please Sign up or sign in to vote.

Transparent GIF

Abstract

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).

CImage

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
public:
   BOOL Flip();
   BOOL Mirror();
   BOOL Negative();
   BOOL GreyScale();
   BOOL Rotate(double angle);
   BOOL Exchange(COLORREF, COLORREF);
   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
CImageGIF
(C++ code)
CImagePNG
(C++ code)
CImageJPEG
(C++ code)
CImageTIFF
(C++ code)
CImageBMP
(C++ code)

CImageIcon
(C++ code)
Windows API +
C Runtime Library
C Runtime Library PNG
(C code)
JPEG
(C code)
TIFF
(C code)
Windows API + C Runtime Library
ZLIB
(C code)
C Runtime Library C Runtime Library C 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.

TO DO:

  • 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.vc -> 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 1.4.0.1 - 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.

License

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

Comments and Discussions

 
Questionhow to disable LNK4049 error warning? Pinmembernenfa20-Apr-10 3:21 
Generalcannot open file "..\lib\imagedll_d.lib" PinmemberRamz862-Nov-08 19:52 
General..\lib\imagedll_d.lib is not found!!! Pinmemberganesa moorthy2-Apr-08 0:07 
Questionconversion from CImage to DIB PinmemberRalf0013-Jul-07 6:18 
Generalcximage.lib(ximatran.obj) : error LNK2001: unresolved external symbol __imp__div Pinmemberdenishernandez7-Feb-06 15:50 
GeneralAnother way to make a PNG file semi transparent PinmemberJockeP17-Oct-05 6:43 
QuestionCan I use IPicture class and work on pixels? PinmemberJoseph Abraham28-Sep-05 1:29 
Questionhow to save the image Pinmemberashwinders14-Jun-05 0:01 
GeneralSystem Error Pinmemberextus11-Oct-04 0:21 
GeneralCImage into Drag&Drop Control PinmemberLen20208-Apr-04 5:11 
GeneralHOWTO: creating a text TRANSPARENT gif Pinmemberemmatty16-Feb-04 0:33 
QuestionWhere are swis.h and kernel.h? Pinmemberlewis.lewis17-Dec-03 8:30 
QuestionHi,Does someone know Image Morpher ? Pinmemberxwshallwe@hotmail.com23-Sep-03 20:23 
GeneralMissing File. PinmemberWREY12-Jul-03 9:34 
GeneralRe: Missing File. PinmemberTRK14-Nov-03 1:26 
Questionhow can I save a transparent gif file? Pinsussgraduate1820-Jun-03 19:37 
GeneralSolved problem en DEBUG mode (LNK2005 errors) Pinmemberchris10910-Jun-03 21:52 
GeneralSetting a skin using PNG from Resource using GDI+ in VC++ 6.0 PinmemberAnthonyDass27-Apr-03 4:30 
GeneralSerialize bug using CImageObject PinmemberBen Mathews18-Mar-03 8:31 
GeneralMFC 7 CImage PinmemberArt Friesz20-Feb-03 14:05 
GeneralRe: MFC 7 CImage PinmemberChristian Graus20-Feb-03 15:02 
GeneralTransparent PNG PinmemberTili16-Feb-03 16:08 
Generaldisplay / printing bitmap PNG files. Pinmembermathison26-Jan-03 20:07 
GeneralPlease Help me Sir PinmemberAnthonyDass27-Apr-03 4:36 
GeneralRe: Please Help me Sir Pinmembergupta_san_9026-Nov-07 23:55 
Questionhow to use plgblt? Pinsusssab02426-Sep-02 0:11 
Questionhow can I get ThumbnailImage? PinsussAnonymous25-Sep-02 17:10 
GeneralUncompressed GIF's using CImage Pinmembernileshwk31-Jul-02 2:47 
QuestionPNG color error? PinsussDereck20-Jul-02 9:16 
AnswerRe: PNG file's color isn't correct! Pinmembersayhappy9-Jan-03 2:41 
GeneralPNG images in CComboBoxEx controls PinmemberMr. Accident27-Jun-02 17:58 
GeneralAny documentation on how VC++ treats JPEG PinmemberSutanu lahiri20-Jun-02 1:14 
QuestionHelp!!! How to show a GIF on the MDI client's background ? PinmemberEric Lee30-May-02 17:43 
GeneralI have a some problem..... Pinmemberpjyou23-May-02 15:47 
GeneralRe: I have a some problem..... PinsussAnonymous8-Jul-04 22:48 
GeneralCImage question - Release PinmemberDelacroix23-May-02 5:52 
QuestionDrawing text on a DC with different bit depths??? PinmemberMikeResar11-Apr-02 23:24 
AnswerRe: Drawing text on a DC with different bit depths??? PinmemberDavide Pizzolato15-Apr-02 10:58 
Generalhave a warning on tiff image Pinmemberericot8-Apr-02 0:27 
GeneralRe: have a warning on tiff image PinmemberMikeResar11-Apr-02 23:34 
Questionhow show a picture jpeg in c or c++ ?? PinmemberAnonymous7-Apr-02 23:43 
AnswerRe: how show a picture jpeg in c or c++ ?? PinmemberChristian Graus8-Apr-02 0:13 
QuestionHow can I move the picture??? PinmemberUnik_Uttam13-Dec-01 23:00 
AnswerRe: How can I move the picture??? PinmemberTroels K.14-Dec-01 3:47 
QuestionPlgBlt? PinmemberQi Yang22-Nov-01 5:37 
GeneralPrinting large high quality images PinmemberPat O'Neil15-Nov-01 12:00 
GeneralRe: Printing large high quality images Pinmembermloibl19-Mar-02 23:26 
Generalcode for bmp file manipulation in C++ PinmemberAnonymous7-Nov-01 22:20 
Sir,
In C++ under dos how to get the pallette and display the bmp file. I know the structure of the bmp file and i could open the file but unable to get the exact image under dos..
and even i have to compress and exapand the file also..
dphaniram@rediffmail.com
sameerupare@rediffmail.com
thanking u'
Generala little question... PinmemberBernhard24-Sep-01 19:22 
GeneralRe: a little question... PinmemberChristian Graus24-Sep-01 19:54 

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

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

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