Harsha Wickramasinghe
Harsha Wickramasinghe

Reputation: 72

How to display an image in a Visual C++ application?

I am trying to display a PNG image in a Visual C++ (2019) application. Its a Win32 dialog based application (I don't use MFC) to show a directory of addresses that contains name, address and a photograph (800x600px). So, all is well except the Photograph. I tried all I knew with the help from Internet but still I could not get it to work. An e.g. of how my app looks like is given below.

enter image description here

What I have tried so far... (1) Added Images as resources (You can see images in the "Resource Files"). (2) Created the Dialog Box where the image would be displayed. (3) Added a Picture Control to the dialog box. (4) Tried to connect the Image to the Picture Control... (~Problem~)

So, I still did not find a way to connect "Picture Control" to the "Image". Appreciate it if you could show me how to do it, or send me a link where it describes the way to do it.

Upvotes: 0

Views: 4758

Answers (1)

user123
user123

Reputation: 2884

The constructor at https://learn.microsoft.com/en-us/windows/win32/api/gdiplusheaders/nf-gdiplusheaders-bitmap-bitmap(constwchar_bool) takes any image file and creates a bitmap out of it (easier to manipulate in program).

#include <gdiplusheaders.h>

Bitmap bmp = Bitmap(L"c:\\users\\user\\restofpath\\image.png"); //Get bitmap
HBITMAP hBitmap;
bmp.GetHBITMAP(0, &hBitmap); //Make it an HBITMAP
HDC hdc = GetDC(hwnd); //Get HDC from window handle (can be any window)
HIMAGELIST imageList = ImageList_Create(640, 480, ILC_COLOR24, 1, 10); //Create image list with images of 640 (width) * 480 (height) and 24 bits rgb
ImageList_Add(imageList, hBitmap, NULL); //Add the bitmap to the imageList
BOOL drawn = ImageList_Draw(imageList, 0, hdc, 0, 0, ILD_IMAGE); //Draw the image on the window
DeleteObject(hBitmap);
ImageList_Destroy(imageList);
DeleteObject(hdc);

You can look at ImageList_Create function for other options: https://learn.microsoft.com/en-us/windows/win32/api/commctrl/nf-commctrl-imagelist_create. Especially the flags section which allows to personalize the type of image to draw. If you want to maintain PNG transparency you might want to use 32 bits DIB.

Upvotes: 1

Related Questions