Click here to Skip to main content
15,867,488 members
Articles / Desktop Programming / MFC
Article

Drawing transparent bitmaps using CImage

Rate me:
Please Sign up or sign in to vote.
4.91/5 (20 votes)
17 Sep 20017 min read 563.1K   13.1K   160   72
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

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

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


Written By
Denmark Denmark
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionProgram is crashing Pin
Member 111823795-Nov-14 18:04
Member 111823795-Nov-14 18: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 17:38
Member 111823795-Nov-14 17:38 
QuestionBlack Backlground on Printing Pin
Rajeev Raina29-Sep-14 23:41
Rajeev Raina29-Sep-14 23:41 
Questionhow to disable LNK4049 error warning? Pin
nenfa20-Apr-10 3:21
nenfa20-Apr-10 3:21 
Generalcannot open file "..\lib\imagedll_d.lib" Pin
Ramz862-Nov-08 19:52
Ramz862-Nov-08 19:52 
General..\lib\imagedll_d.lib is not found!!! Pin
ganesa moorthy2-Apr-08 0:07
ganesa moorthy2-Apr-08 0:07 
Questionconversion from CImage to DIB Pin
Ralf0013-Jul-07 6:18
Ralf0013-Jul-07 6:18 
Generalcximage.lib(ximatran.obj) : error LNK2001: unresolved external symbol __imp__div Pin
denishernandez7-Feb-06 15:50
denishernandez7-Feb-06 15:50 
GeneralAnother way to make a PNG file semi transparent Pin
JockeP17-Oct-05 6:43
JockeP17-Oct-05 6:43 
QuestionCan I use IPicture class and work on pixels? Pin
Joseph Abraham28-Sep-05 1:29
Joseph Abraham28-Sep-05 1:29 
Questionhow to save the image Pin
ashwinders14-Jun-05 0:01
ashwinders14-Jun-05 0:01 
GeneralSystem Error Pin
extus11-Oct-04 0:21
extus11-Oct-04 0:21 
GeneralCImage into Drag&Drop Control Pin
Len20208-Apr-04 5:11
Len20208-Apr-04 5:11 
GeneralHOWTO: creating a text TRANSPARENT gif Pin
emmatty16-Feb-04 0:33
emmatty16-Feb-04 0:33 
hello friends,

We are doing a project in vc++ for image processing .We used your class(CXImage) in our project for converting user typed text into transparent GIF image. We used the following steps for our requirement.

Note: Operating System : Win XP Professional ,
Development Tool : VC++ 6.0.

1)Create a memoryDC

2)Created a compatible bitmap with the dialog

3)selected the bitmap into MemoryDC

4)Draw Text on that DC

5) Created a CXImage object and passed Bitmap handle to CXImage member function called CreateFromHBITMAP

6) We used the function Save() to save that image.

But the problem ia that we can insert the Image to Frontpage but the image is not visible.
Following code is extracted from our project
void CTestCXImageDlg::OnCreateBMP()
{
CDC memDC;
CBitmap bitmap;
CBrush brush(RGB(255,255,255));
CFont font;
UpdateData();

font.CreateFontIndirect(&logfont);

if(memDC.CreateCompatibleDC(GetDC()))
{
if(bitmap.CreateCompatibleBitmap(GetDC(),200,50))
{
memDC.SelectObject(bitmap);

memDC.SetBkColor(RGB(255,255,255));
memDC.FillRect(CRect(0,0,200,50),&brush);
CRect rect(60,15,200,50);
SetTextColor(memDC.m_hDC,RGB(0,255,0));

memDC.SelectObject(&font);

memDC.DrawText(m_Text,&rect,DT_END_ELLIPSIS | DT_CENTER );

CxImage img1;
img1.CreateFromHBITMAP((HBITMAP)bitmap.m_hObject);

img1.Save("c:\\imgtest.gif",1);
.
.
.
.

eagerly waiting for your response

QuestionWhere are swis.h and kernel.h? Pin
Member 59885217-Dec-03 8:30
Member 59885217-Dec-03 8:30 
QuestionHi,Does someone know Image Morpher ? Pin
Member 59693623-Sep-03 20:23
Member 59693623-Sep-03 20:23 
GeneralMissing File. Pin
WREY12-Jul-03 9:34
WREY12-Jul-03 9:34 
GeneralRe: Missing File. Pin
TRK14-Nov-03 1:26
TRK14-Nov-03 1:26 
Questionhow can I save a transparent gif file? Pin
herbert1820-Jun-03 19:37
herbert1820-Jun-03 19:37 
GeneralSolved problem en DEBUG mode (LNK2005 errors) Pin
chris10910-Jun-03 21:52
chris10910-Jun-03 21:52 
GeneralSetting a skin using PNG from Resource using GDI+ in VC++ 6.0 Pin
Anthony Dass27-Apr-03 4:30
Anthony Dass27-Apr-03 4:30 
GeneralSerialize bug using CImageObject Pin
Ben Mathews18-Mar-03 8:31
Ben Mathews18-Mar-03 8:31 
GeneralMFC 7 CImage Pin
Big Art20-Feb-03 14:05
Big Art20-Feb-03 14:05 
GeneralRe: MFC 7 CImage Pin
Christian Graus20-Feb-03 15:02
protectorChristian Graus20-Feb-03 15:02 
GeneralTransparent PNG Pin
Tili16-Feb-03 16:08
Tili16-Feb-03 16: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.