How to Load a Bitmap from a Resource (Windows Imaging Component)
This topic demonstrates how to load an IWICBitmapFrameDecode from an application resource.
In the application resource definition (.rc) file , define the resource. The following example defines an
Image
resource namedIDR_SAMPLE_IMAGE
.IDR_SAMPLE_IMAGE IMAGE "turtle.jpg"
The resource will be added to the application's resources when the application is built.
Load the resource from the application.
HRESULT hr = S_OK; // WIC interface pointers. IWICStream *pIWICStream = NULL; IWICBitmapDecoder *pIDecoder = NULL; IWICBitmapFrameDecode *pIDecoderFrame = NULL; // Resource management. HRSRC imageResHandle = NULL; HGLOBAL imageResDataHandle = NULL; void *pImageFile = NULL; DWORD imageFileSize = 0; // Locate the resource in the application's executable. imageResHandle = FindResource( NULL, // This component. L"SampleImage", // Resource name. L"Image"); // Resource type. hr = (imageResHandle ? S_OK : E_FAIL); // Load the resource to the HGLOBAL. if (SUCCEEDED(hr)){ imageResDataHandle = LoadResource(NULL, imageResHandle); hr = (imageResDataHandle ? S_OK : E_FAIL); }
Lock the resource and get the size.
// Lock the resource to retrieve memory pointer. if (SUCCEEDED(hr)){ pImageFile = LockResource(imageResDataHandle); hr = (pImageFile ? S_OK : E_FAIL); } // Calculate the size. if (SUCCEEDED(hr)){ imageFileSize = SizeofResource(NULL, imageResHandle); hr = (imageFileSize ? S_OK : E_FAIL); }
Use the CreateStream method to create an IWICStream object and initialize it by using the image memory pointer.
// Create a WIC stream to map onto the memory. if (SUCCEEDED(hr)){ hr = m_pIWICFactory->CreateStream(&pIWICStream); } // Initialize the stream with the memory pointer and size. if (SUCCEEDED(hr)){ hr = pIWICStream->InitializeFromMemory( reinterpret_cast<BYTE*>(pImageFile), imageFileSize); }
Create an IWICBitmapDecoder from the new stream object by using the CreateDecoderFromStream method.
// Create a decoder for the stream. if (SUCCEEDED(hr)){ hr = m_pIWICFactory->CreateDecoderFromStream( pIWICStream, // The stream to use to create the decoder NULL, // Do not prefer a particular vendor WICDecodeMetadataCacheOnLoad, // Cache metadata when needed &pIDecoder); // Pointer to the decoder }
Retrieve an IWICBitmapFrameDecode from the decoded image.
// Retrieve the initial frame. if (SUCCEEDED(hr)){ hr = pIDecoder->GetFrame(0, &pIDecoderFrame); }
This code only retrieves the first (
0
) frame of the image. For multi-framed images, use GetFrameCount to determine the number of frames in the image.
See Also