4

I am new to C++ and been having trouble with writing a function using the GDI+ library to create a new bitmap in memory ( so not opening/reading an existing bitmap); then drawing on the bitmap; before saving it to png. In particular, I am having problems with the bitmap creation and saving code. I am constrained to using codeblocks and I can't use visual studios, even if I wanted to. The code is as follows:

#include "drawImage.h"
#include <windows.h>
#include <objidl.h>
#include <gdiplus.h>
#include <stdio.h>
#include <iostream>
using namespace std;
using namespace Gdiplus;

drawImage::drawImage(){}

void drawImage::DrawBitmap(int width, int height){
  GdiplusStartupInput gdiplusStartupInput;
  ULONG_PTR           gdiplusToken;
  GdiplusStartup(&gdiplusToken, &gdiplusStartupInput, NULL);

  {
    //Create a bitmap
    Bitmap myBitmap(width, height, PixelFormatCanonical);
    Graphics g(&myBitmap);
    Pen blackpen(Color(255,0,0,0), 3);

    //draw on bitmap
    int x1 = 1;
    int x2 = 200;
    int y1 = 1;
    int y2 = 200;
    g.DrawLine(&blackpen, x1,y1,x2,y2);

    // Save bitmap (as a png)
    CLSID pngClsid;
    GetEncoderClsid(L"image/png", &pngClsid);
    myBitmap.Save(L"C:\\test\\test.png", &pngClsid, NULL);
  }

  GdiplusShutdown(gdiplusToken);
}

The issues I am having are as follows:

  1. The 'saving' code does not compile and gives the error message "'GetEncoderClsid' was not declared in this scope". However, I got this direct from the Microsoft website here. I don't think this is the proper way of converting to png but I dont know an alternative way?

  2. When the code is compiled and run (by commenting out the saving code), it then crashes on the line "Bitmap *myBitmap = new Bitmap(width, height, PixelFormatCanonical);" and gives an error message saying my executable has stopped working.

I have added the 'gdi32' linker library and also '-lgdiplus' as a linker option. Also, I have used this website to help with the gdi stuff although the section on bitmaps only deals with loading existing bitmaps (not creating new ones in memory)

I am totally lost on what to do, so any help or advice on this matter is much appreciated.

22
  • How is drawImage defined? How do you call (with what arguments) DrawBitmap?
    – user4407569
    Sep 17, 2016 at 21:34
  • Off-topic: You are allocating a new object with new but you never delete it when it is no longer needed. That is bad and results in memory leak as soon as you leave DrawBitmap.
    – user4407569
    Sep 17, 2016 at 21:36
  • Thanks for the delete advice. I come from programming languages that use garbage collectors. so I am still learing how to do this type of memory management (so I will now delete it at the end of the function). As for your drawImage query, this code is very much exemplar code in order to keep it specific to the problem but I created a class in codeblocks and this is the .cpp code. the main library calls it by the following: drawImage di; di.DrawBitmap(250, 250); (with #include "drawImage.h" as an include statement)
    – greenbeast
    Sep 17, 2016 at 21:43
  • 1
    Image::Save has a return value. Sep 17, 2016 at 22:29
  • 1
    I don't know what is PixelFormatCanonical. Just remove that or use the values from here. For example Bitmap myBitmap(width, height); Sep 17, 2016 at 22:53

2 Answers 2

10

The core issue is passing the wrong pixel format to the Bitmap constructor. PixelFormatCanonical is not one of the supported pixel formats. It's a bit mask used to determine whether a pixel format is canonical (see IsCanonicalPixelFormat). You'll have to use a real pixel format, like the default PixelFormat32bppARGB.

The following code produces the desired output:

First up, a small helper class for GDI+ initialization. This ensures, that the d'tor (i.e. the call to GdiplusShutdown) is executed after all other objects have been destroyed. With respect to order of destruction, it serves the same purpose as the additional scope in the OP. In addition, it also allows for exceptions to be thrown.

#include <windows.h>
#include <gdiplus.h>
using namespace Gdiplus;
#include <stdexcept>
using std::runtime_error;

struct GdiplusInit {
    GdiplusInit() {
        GdiplusStartupInput inp;
        GdiplusStartupOutput outp;
        if ( Ok != GdiplusStartup( &token_, &inp, &outp ) )
            throw runtime_error( "GdiplusStartup" );
    }
    ~GdiplusInit() {
        GdiplusShutdown( token_ );
    }
private:
    ULONG_PTR token_;
};

This code was taken from the MSDN sample Retrieving the Class Identifier for an Encoder.

int GetEncoderClsid( const WCHAR* format, CLSID* pClsid )
{
    UINT  num = 0;          // number of image encoders
    UINT  size = 0;         // size of the image encoder array in bytes

    ImageCodecInfo* pImageCodecInfo = NULL;

    GetImageEncodersSize( &num, &size );
    if ( size == 0 )
        return -1;  // Failure

    pImageCodecInfo = (ImageCodecInfo*)( malloc( size ) );
    if ( pImageCodecInfo == NULL )
        return -1;  // Failure

    GetImageEncoders( num, size, pImageCodecInfo );

    for ( UINT j = 0; j < num; ++j )
    {
        if ( wcscmp( pImageCodecInfo[j].MimeType, format ) == 0 )
        {
            *pClsid = pImageCodecInfo[j].Clsid;
            free( pImageCodecInfo );
            return j;  // Success
        }
    }

    free( pImageCodecInfo );
    return -1;  // Failure
}

Finally, the GDI+ rendering code. It uses objects with automatic storage duration throughout, making it more compact and safer.

void drawImage( int width, int height ) {
    GdiplusInit gdiplusinit;

    //Create a bitmap
    Bitmap myBitmap( width, height, PixelFormat32bppARGB );
    Graphics g( &myBitmap );
    Pen blackpen( Color( 255, 0, 0, 0 ), 3 );

    //draw on bitmap
    g.DrawLine( &blackpen, 1, 1, 200, 200 );

    // Save bitmap (as a png)
    CLSID pngClsid;
    int result = GetEncoderClsid( L"image/png", &pngClsid );
    if ( result == -1 )
        throw runtime_error( "GetEncoderClsid" );
    if ( Ok != myBitmap.Save( L"C:\\test\\test.png", &pngClsid, NULL ) )
        throw runtime_error( "Bitmap::Save" );
}

int main()
{
    drawImage( 200, 200 );
    return 0;
}

Note: It looks like GetEncoderClsid shouldn't be required, since those are well-known constants. However, trying to pass the appropriate WIC CLSID (CLSID_WICPngEncoder) to Bitmap::Save only produced a FileNotFound error.

4

For 1.: GetEncoderClsid is not a library function, it is an example helper defined here. If you want to use it copy the code from the site. (Btw your link explicitly states this.)

For 2.: You need to call GdiplusStartup before creating any GDI+ object or calling any GDI+ function. See its documentation here.

To be more precise about GdiplusShutdown because that seems to be making you new problems: It is required that all GDI+ objects are destroyed before GdiplusShutdown is called. That means that objects with static storage (for example pen) must go out of scope before GdiplusShutdown is called. That is not the case if you call it in DrawBitmap in the way you do now. Either call GdiplusStartup and GdiplusShutdown in main or add additional brackets {} around your code between GdiplusStartup and GdiplusShutdown, because these introduce a new scope and pen would be destroyed when } is reached.

Edit: Nr. 2 was fixed in the question by edit. For the remaining problem and improvement of the code see @IInspectable's answer.

2
  • Many thanks and apologise as I should have been more thorough and caught that. I wont mark this as an answer as it only partially answers the quesiton. Also, I don't know yet (as the code crashes) if this will successfully convert the bitmap to png and then save it. But again thank you and your response is fully appreciated.
    – greenbeast
    Sep 17, 2016 at 21:35
  • Many thanks to you Eichhornchen and also Ilnspectable. Your help has been invaluable.
    – greenbeast
    Sep 17, 2016 at 23:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.