我正在尝试根据此How to save ID2D1Bitmap to PNG file保存ID2D1Bitmap,但与他不同的是hr = pRT2-> EndDraw();我的小时= -2003238891。这意味着D2DERR_WRONG_RESOURCE_DOMAIN。我如何使用源渲染目标(pRenderTarget)来解决这个问题?
bitmapToFile.cpp
HRESULT bitmapToFile::SaveBitmapToFile(PCWSTR uri,ID2D1Bitmap* pBitmap,ID2D1RenderTarget* pRenderTarget)
{
HRESULT hr = S_OK;
IWICBitmap *pWICBitmap = NULL;
ID2D1RenderTarget *pRT2 = NULL;
IWICBitmapEncoder *pEncoder = NULL;
IWICBitmapFrameEncode *pFrameEncode = NULL;
IWICStream *pStream = NULL;
if (SUCCEEDED(hr))
{
// Create a WIC factory.
CoCreateInstance(
CLSID_WICImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_IWICImagingFactory,
reinterpret_cast<void **>(&m_pWICFactory)
);
}
UINT sc_bitmapWidth = pBitmap->GetSize().width;
UINT sc_bitmapHeight = pBitmap->GetSize().height;
if (SUCCEEDED(hr))
{
hr = m_pWICFactory->CreateBitmap(
sc_bitmapWidth,
sc_bitmapHeight,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapCacheOnLoad,
&pWICBitmap
);
}
if (SUCCEEDED(hr))
{
D2D1_RENDER_TARGET_PROPERTIES rtProps = D2D1::RenderTargetProperties();
rtProps.pixelFormat = D2D1::PixelFormat(DXGI_FORMAT_B8G8R8A8_UNORM, D2D1_ALPHA_MODE_PREMULTIPLIED);
rtProps.type = D2D1_RENDER_TARGET_TYPE_DEFAULT;
rtProps.usage = D2D1_RENDER_TARGET_USAGE_NONE;
hr = m_pD2DFactory2->CreateWicBitmapRenderTarget(
pWICBitmap,
rtProps,
&pRT2
);
}
if (SUCCEEDED(hr))
{
pRT2->BeginDraw();
pRT2->Clear();
pRT2->DrawBitmap(pBitmap);
hr=pRT2->EndDraw();
}
if (SUCCEEDED(hr))
{
hr = m_pWICFactory->CreateStream(&pStream);
}
WICPixelFormatGUID format = GUID_WICPixelFormat32bppPBGRA;
if (SUCCEEDED(hr))
{
hr = pStream->InitializeFromFilename(uri, GENERIC_WRITE);
}
if (SUCCEEDED(hr))
{
hr = m_pWICFactory->CreateEncoder(GUID_ContainerFormatPng, NULL, &pEncoder);
}
if (SUCCEEDED(hr))
{
hr = pEncoder->Initialize(pStream, WICBitmapEncoderNoCache);
}
if (SUCCEEDED(hr))
{
hr = pEncoder->CreateNewFrame(&pFrameEncode, NULL);
}
if (SUCCEEDED(hr))
{
hr = pFrameEncode->Initialize(NULL);
}
if (SUCCEEDED(hr))
{
hr = pFrameEncode->SetSize(sc_bitmapWidth, sc_bitmapHeight);
}
if (SUCCEEDED(hr))
{
hr = pFrameEncode->SetPixelFormat(&format);
}
if (SUCCEEDED(hr))
{
hr = pFrameEncode->WriteSource(pWICBitmap, NULL);
}
if (SUCCEEDED(hr))
{
hr = pFrameEncode->Commit();
}
if (SUCCEEDED(hr))
{
hr = pEncoder->Commit();
}
return hr;
}
答案 0 :(得分:0)
主要问题是使用默认渲染属性创建的渲染目标(源ID2D1RenderTarget和目标WIC rendertarget)。根据{{3}},无法在具有默认属性的目标之间共享资源,因为不知道位图将在何处呈现。所以在我的情况下,我用这些属性创建了两个目标:
auto rtProps = D2D1::RenderTargetProperties();
rtProps.type = D2D1_RENDER_TARGET_TYPE_SOFTWARE;
rtProps.usage = D2D1_RENDER_TARGET_USAGE_GDI_COMPATIBLE;
之后,WIC渲染成功绘制源位图。