Note

Access to this page requires authorization. You can try signing in or .

Access to this page requires authorization. You can try .

How to Load a Bitmap from a File

Direct2D uses the Windows Imaging Component (WIC) to load bitmaps. To load a bitmap from a file, first use WIC objects to load the image and to convert it to a Direct2D-compatible format, then use the CreateBitmapFromWicBitmap method to create an ID2D1Bitmap.

  1. Create an IWICBitmapDecoder by using the IWICImagingFactory::CreateDecoderFromFileName method.

    HRESULT DemoApp::LoadBitmapFromFile(
     ID2D1RenderTarget *pRenderTarget,
     IWICImagingFactory *pIWICFactory,
     PCWSTR uri,
     UINT destinationWidth,
     UINT destinationHeight,
     ID2D1Bitmap **ppBitmap
     )
    {
     IWICBitmapDecoder *pDecoder = NULL;
     IWICBitmapFrameDecode *pSource = NULL;
     IWICStream *pStream = NULL;
     IWICFormatConverter *pConverter = NULL;
     IWICBitmapScaler *pScaler = NULL;
    
     HRESULT hr = pIWICFactory->CreateDecoderFromFilename(
     uri,
     NULL,
     GENERIC_READ,
     WICDecodeMetadataCacheOnLoad,
     &pDecoder
     );
    
    
  2. Retrieve a frame from the image and store the frame in an IWICBitmapFrameDecode object.

     if (SUCCEEDED(hr))
     {
     // Create the initial frame.
     hr = pDecoder->GetFrame(0, &pSource);
     }
    
  3. The bitmap must be converted to a format that Direct2D can use, so convert the image's pixel format to 32bppPBGRA. (For a list of supported formats, see Pixel Formats and Alpha Modes.). Call the IWICImagingFactory::CreateFormatConverter method to create an IWICFormatConverter object, then call the IWICFormatConverter object's Initialize method to perform the conversion.

     if (SUCCEEDED(hr))
     {
    
     // Convert the image format to 32bppPBGRA
     // (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED).
     hr = pIWICFactory->CreateFormatConverter(&pConverter);
    
     }
    
    
     if (SUCCEEDED(hr))
     {
     hr = pConverter->Initialize(
     pSource,
     GUID_WICPixelFormat32bppPBGRA,
     WICBitmapDitherTypeNone,
     NULL,
     0.f,
     WICBitmapPaletteTypeMedianCut
     );
    
  4. Call the CreateBitmapFromWicBitmap method to create an ID2D1Bitmap object that can be drawn by a render target and used with other Direct2D objects.

     if (SUCCEEDED(hr))
     {
    
     // Create a Direct2D bitmap from the WIC bitmap.
     hr = pRenderTarget->CreateBitmapFromWicBitmap(
     pConverter,
     NULL,
     ppBitmap
     );
     }
    
     SafeRelease(&pDecoder);
     SafeRelease(&pSource);
     SafeRelease(&pStream);
     SafeRelease(&pConverter);
     SafeRelease(&pScaler);
    
     return hr;
    }
    

Some code has been omitted from this example.

Related topics

ID2D1Bitmap

CreateBitmapFromWicBitmap

How to Load a Bitmap from a Resource


Feedback

Was this page helpful?

Additional resources