65.9K
CodeProject is changing. Read more.
Home

PNGView

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.64/5 (23 votes)

Aug 3, 2005

1 min read

viewsIcon

263563

downloadIcon

6147

Load and display PNG files in MFC.

Sorry, it should have been PNGView.jpg

Introduction

This is a very simple approach to display PNG files in MFC. Two common libraries provide the needed functionality: zlib and libpng. These libraries are included in the source file.

Background

I had been searching the net for a really simple PNG example for a whole while. But all I found were C files that contained more preprocessor directives than keywords. I don't like preprocessor directives so I've written this example. It uses only one class to do the whole stuff.

Using the code

At first:

You might have to upgrade your include-folder settings, because libpng wants to know where your zlib.h is located. After you have unzipped the downloaded archive, you can find this file in the ...\zlib\code\ folder.

The FileOpen handler:

This chunk of code works off both reading and showing the PNG file:

// create temporary object
PngImage png;

// import png file
if ( png.load(dlg.GetPathName()) )
{
    // get size
    int width  = png.getWidth();
    int height = png.getHeight();

    // get blue, green, red and alpha values
    unsigned char* data = png.getBGRA();

    // free memory first
    if (m_bitmap) delete m_bitmap;
    if (m_visible) delete m_visible;

    // create a CBitmap to display
    m_bitmap = doCreateCompatibleBitmap(width, height, data, this);

    // used to speed up OnPaint()
    m_visible = doZoomBitmap(m_bitmap, this);

    // request graphical update
    Invalidate();
    UpdateWindow();
}

History

Version 1.3

Added:

  • Reading 1, 2 and 4 bit monochrome images.
  • Reading 1, 2 and 4 bit monochrome images with transparency.
  • Reading images that use a palette.

Version 1.2

Changed:

  • Displaying the CBitmap object got faster.

Version 1.1

Not submitted

Version 1.0

Added:

  • Reading 8-bit RGB images.
  • Reading 8-bit RGB images with transparency.
  • Reading 8-bit monochrome images.
  • Reading 8-bit monochrome images with transparency.