Direct2D 加载位图

时间:2022-03-02 09:04:20

说明:

通过WIC从文件加载位图.

可缩放后加载到内存.

源码:
 HRESULT LoadImageFormFile(
                           IWICImagingFactory *pWicFactory,
                           ID2D1RenderTarget *pRT,
                           PCTSTR fname,
                           DWORD dstWidth,
                           DWORD dstHeight,
                           ID2D1Bitmap **ppBitmap
                           )
 {
     IWICBitmapDecoder *pDecoder = NULL;
     IWICBitmapFrameDecode *pFrame = NULL;
     IWICBitmapScaler *pScaler = NULL;
     IWICFormatConverter *pFormat =  NULL;  

     HRESULT hr = pWicFactory->CreateDecoderFromFilename(
         fname,
         NULL,
         GENERIC_READ,
         WICDecodeMetadataCacheOnLoad,
         &pDecoder
         );

     if ( SUCCEEDED(hr) )
     {
         hr = pDecoder->GetFrame(, &pFrame);
     }

     if ( SUCCEEDED(hr) )
     {
         hr = pWicFactory->CreateFormatConverter(&pFormat);
     }

     UINT width, height;
     if ( SUCCEEDED(hr) )
     {
         hr = pFrame->GetSize(&width, &height);
     }

     if ( SUCCEEDED(hr) )
     {
         if (width)
         {
             FLOAT scalar = (FLOAT)dstWidth / (FLOAT)width;
             width = (UINT)(width * scalar);
         }
         if (height)
         {
             FLOAT scalar = (FLOAT)dstHeight / (FLOAT)height;
             height = (UINT)(height * scalar);
         }
         hr = pWicFactory->CreateBitmapScaler(&pScaler);
     }

     if ( SUCCEEDED(hr) )
     {
         hr = pScaler->Initialize(pFrame, width, height, WICBitmapInterpolationModeCubic);
     }

     if (SUCCEEDED(hr))
     {
         hr = pFormat->Initialize(pScaler, GUID_WICPixelFormat32bppPBGRA, WICBitmapDitherTypeNone, NULL, 0.0f, WICBitmapPaletteTypeMedianCut);
     }

     if ( SUCCEEDED(hr) )
     {
         hr = pRT->CreateBitmapFromWicBitmap(pFormat, ppBitmap);
     }
     SafeRelease(pDecoder);
     SafeRelease(pFrame);
     SafeRelease(pScaler);
     SafeRelease(pFormat);
     return hr;
 }