Home Articles Books Downloads FAQs Tips

Q: Add JPEG images as resources to the program


Answer

This FAQ combines the FAQ on displaying JPEG images with the FAQ on how to add icon, cursor, bitmap, and sound resources to a BCB project. Here is how it works.

Step 1 - Make a .RH resource header file that looks like this:

// resource.rh
#ifndef RESOURCE_RH
#define RESOURCE_RH

#define ID_JPEG     1000
#endif

Step 2 - Make a .RC resource file that lists the JPEG as an RCDATA resource type.

#include "resource.rh"

ID_JPEG    RCDATA   "conf99.JPG"

Step 3 - Add the .RC file to your project

Step 4 - Place an image on the form somewhere.

Step 5 - Run this code to load the image from resource.

#include <jpeg.hpp>
#include "main.h"
#include "resource.rh"

...

void __fastcall TForm1::Button1Click(TObject *Sender)
{
    // Find the resource using the resource ID from resource.rh
    HRSRC rsrc = FindResource(HInstance, MAKEINTRESOURCE(ID_JPEG),RT_RCDATA);
    if(!rsrc)
        return;

    // Load the resource and save its total size. We will need the size
    // when we read the data.
    DWORD Size = SizeofResource(HInstance , rsrc);
    HGLOBAL MemoryHandle = LoadResource(HInstance,rsrc);
    if(MemoryHandle == NULL)
        return;

    // We need to get the bytes out of the resource somehow.
    // The API function LockResource allows us to do that.
    // It returns a BYTE pointer to the raw data in the resource
    // In this case, the resource is a .JPG file.
    BYTE *MemPtr = (BYTE *)LockResource(MemoryHandle);

    // Now the jpeg image is memory is in MemPtr.
    // Copy from MemPtr into a TMemoryStream
    std::auto_ptr<TMemoryStream>stream(new TMemoryStream);
    stream->Write(MemPtr, Size);
    stream->Position = 0;

    // Create a TJPEGImage, and tell it to load from the memory stream.
    std::auto_ptr<TJPEGImage> JImage(new TJPEGImage());
    JImage->LoadFromStream(stream.get());

    // Now that we have a TJEGImage, we can use Assign to
    // copy that image into a TImage.
    MyImage->Width  = JImage->Width;
    MyImage->Height = JImage->Height;
    MyImage->Picture->Assign(JImage.get());
}


Downloads for this FAQ
faq90.zip Source code for this FAQ.


Copyright © 1997-2000 by Harold Howe.
All rights reserved.