Direct2D Loading and Drawing Bitmap - c++

I'm trying to draw a bitmap to the screen; the code that calls to load the bitmap from a file works, but it seems the actual drawing part is causing some program crashes.
I followed a tutorial from MSDN, but the only change I made was instead of using ID2D1RenderTarget, I'm using a ID2D1DCRenderTarget.
Here's the Load method that works:
HRESULT LoadBitmapFromFile(
ID2D1DCRenderTarget *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
);
if (SUCCEEDED(hr))
{
// Create the initial frame.
hr = pDecoder->GetFrame(0, &pSource);
}
if (SUCCEEDED(hr))
{
// Convert the image format to 32bppPBGRA
// (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED).
hr = pIWICFactory->CreateFormatConverter(&pConverter);
}
if (SUCCEEDED(hr))
{
// If a new width or height was specified, create an
// IWICBitmapScaler and use it to resize the image.
if (destinationWidth != 0 || destinationHeight != 0)
{
UINT originalWidth, originalHeight;
hr = pSource->GetSize(&originalWidth, &originalHeight);
if (SUCCEEDED(hr))
{
if (destinationWidth == 0)
{
FLOAT scalar = static_cast<FLOAT>(destinationHeight) / static_cast<FLOAT>(originalHeight);
destinationWidth = static_cast<UINT>(scalar * static_cast<FLOAT>(originalWidth));
}
else if (destinationHeight == 0)
{
FLOAT scalar = static_cast<FLOAT>(destinationWidth) / static_cast<FLOAT>(originalWidth);
destinationHeight = static_cast<UINT>(scalar * static_cast<FLOAT>(originalHeight));
}
hr = pIWICFactory->CreateBitmapScaler(&pScaler);
if (SUCCEEDED(hr))
{
hr = pScaler->Initialize(
pSource,
destinationWidth,
destinationHeight,
WICBitmapInterpolationModeCubic
);
}
if (SUCCEEDED(hr))
{
hr = pConverter->Initialize(
pScaler,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
NULL,
0.f,
WICBitmapPaletteTypeMedianCut
);
}
}
}
else // Don't scale the image.
{
hr = pConverter->Initialize(
pSource,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
NULL,
0.f,
WICBitmapPaletteTypeMedianCut
);
}
}
if (SUCCEEDED(hr))
{
// Create a Direct2D bitmap from the WIC bitmap.
hr = pRenderTarget->CreateBitmapFromWicBitmap(
pConverter,
NULL,
ppBitmap
);
}
if (pDecoder) pDecoder->Release();
if (pSource) pSource->Release();
if (pStream) pStream->Release();
if (pScaler) pScaler->Release();
return hr;
}
And in between the BeginDraw() and EndDraw() for the render target, I have the following code to draw the bitmap. This is the part that crashes the program when I attempt to run it:
d2dg->pRT->BeginDraw();
// Create a WIC Factory
HRESULT hr = CoCreateInstance(
CLSID_WICImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_IWICImagingFactory,
(LPVOID*)&wicFactory);
hr = LoadBitmapFromFile(d2dg->pRT, wicFactory, L"image1.png", 400, 400, &pBitmap);
D2D1_SIZE_F size = pBitmap->GetSize();
D2D1_POINT_2F upperLeftCorner = D2D1::Point2F(100.f, 10.f);
// Draw a bitmap.
d2dg->pRT->DrawBitmap(
pBitmap,
D2D1::RectF(
upperLeftCorner.x,
upperLeftCorner.y,
upperLeftCorner.x + size.width,
upperLeftCorner.y + size.height)
);
d2dg->pRT->EndDraw();

Found the issue to this: the bitmap I wanted to draw was still NULL.
This can be fixed by deleting the ID2D1Bitmap **ppBitmap parameter from LoadBitmapFromFile and just work with the pointer to &pBitmap for any references to a bitmap within the method.
That way, pBitmap gets manipulated and will not remain NULL.

Related

How to get pixeldata without using LockRect? (Performance issue)

I'm using these function someone post on StackOverflow, but the performance is toooooooo bad..
With out using this function( not capture pixel ) FPS show over 6k, but using this function, FPS show only 60!
So is there any fast method that can copy between video memory and system memory?
Anyone please?
HRESULT capture(IDirect3DDevice9* m_d3ddev, void* buffer, int& width, int& height, D3DFORMAT format)
{
IDirect3DSurface9 *renderTarget = NULL;
IDirect3DSurface9 *destTarget = NULL;
HRESULT hr = m_d3ddev->GetRenderTarget(0, &renderTarget);
hr = m_d3ddev->CreateOffscreenPlainSurface(width, height, format, D3DPOOL_SYSTEMMEM, &destTarget, NULL);
if (FAILED(hr))
{
printf("Failed CreateOffscreenPlainSurface!");
}
hr = m_d3ddev->GetRenderTargetData(renderTarget, destTarget);
if (FAILED(hr))
{
printf("Failed GetRenderTargetData!");
}
D3DLOCKED_RECT lr;
ZeroMemory(&lr, sizeof(D3DLOCKED_RECT));
hr = destTarget->LockRect(&lr, 0, D3DLOCK_READONLY);
if (FAILED(hr))
{
printf("Cannot lock rect!");
}
if (lr.pBits)
{
memcpy(buffer, lr.pBits, width * height * 4);
}
hr = destTarget->UnlockRect();
if (FAILED(hr))
{
printf("Cannot unlock rect!");
}
renderTarget->Release();
destTarget->Release();
return hr;
}

following "What's a Creel?"s tutorial: Can't create a IWICBitmapDecoder, in visual studio 2015

I've been following "what's a Creel?"'s tutorial for direct 2d. I got to tutorial 8: 'Loading an image'. I didn't have the spritesheet object save the pointer to the Graphics object as this caused problems with this version of visual studio, so it's passed every time something needing it is called. main point: when I try creating a IWICBitmapDecoder with the wicfactory->CreateDecoderFromFile() method, I get the following error:
Exception thrown at 0x008C70A7 in Project8.exe: 0xC0000005: Access violation reading location 0x00000000.
and in the Autos I get:
hr | E_NOINTERFACE No such interface supported.
this | 0x00c1a5c8 {bmp=0x00000000 <NULL> } spritesheet *
wicfactory | 0x00000000<NULL>
wicdecoder | 0xcccccccc{...}
the code being this:
#pragma once
#include <wincodec.h> //include windowscodecs.lib in the linker input
#include "Graphics.h"
#include <d2d1.h>
#include<string>
class spritesheet {
public:
ID2D1Bitmap* bmp;
spritesheet() {}
spritesheet(LPCWSTR file, graphics* gfx) {
//this->gfx = gfx;
//bmp = NULL;
HRESULT hr;
//create an image factory
IWICImagingFactory *wicFactory;
hr = CoCreateInstance(
CLSID_WICImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
CLSID_WICImagingFactory,
(LPVOID*)&wicFactory
);
//create a decoder
IWICBitmapDecoder *wicdecoder;
hr = wicFactory->CreateDecoderFromFilename(
file,
NULL,
GENERIC_READ,
WICDecodeMetadataCacheOnLoad,
&wicdecoder
);
IWICBitmapFrameDecode* wicframe = NULL;
hr = wicdecoder->GetFrame(0, &wicframe);
IWICFormatConverter *wicconverter = NULL;
hr = wicFactory->CreateFormatConverter(&wicconverter);
hr = wicconverter->Initialize(
wicframe,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
NULL,
0.0,
WICBitmapPaletteTypeCustom
);
gfx->gettarget()->CreateBitmapFromWicBitmap(
wicconverter,
NULL,
&bmp
);
if (wicdecoder) wicdecoder->Release();
if (wicFactory) wicFactory->Release();
if (wicconverter) wicconverter->Release();
if (wicframe) wicframe->Release();
}
void init(wchar_t * file, graphics * gfx) {
//this->gfx = gfx;
//bmp = NULL;
HRESULT hr;
//create an image factory
IWICImagingFactory* wicFactory;
hr = CoCreateInstance(
CLSID_WICImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
CLSID_WICImagingFactory,
(LPVOID*)&wicFactory
);
//create a decoder
IWICBitmapDecoder* wicdecoder;
hr = wicFactory->CreateDecoderFromFilename(
file,
NULL,
GENERIC_READ,
WICDecodeMetadataCacheOnLoad,
&wicdecoder
);
IWICBitmapFrameDecode* wicframe = NULL;
hr = wicdecoder->GetFrame(0, &wicframe);
IWICFormatConverter *wicconverter = NULL;
hr = wicFactory->CreateFormatConverter(&wicconverter);
hr = wicconverter->Initialize(
wicframe,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
NULL,
0.0,
WICBitmapPaletteTypeCustom
);
gfx->rendertarget->CreateBitmapFromWicBitmap(
wicconverter,
NULL,
&bmp
);
if (wicdecoder) wicdecoder->Release();
if (wicFactory) wicFactory->Release();
if (wicconverter) wicconverter->Release();
if (wicframe) wicframe->Release();
gfx->rendertarget->DrawBitmap(
bmp,
D2D1::RectF(0.0f, 0.0f, 10, 10), //dest rect
1.0f,
D2D1_BITMAP_INTERPOLATION_MODE::D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR, //effect for scaling
D2D1::RectF(0, 0, 10, 10)); //scource rect
}
void draw(graphics *gfx) {
gfx->rendertarget->DrawBitmap(
bmp,
D2D1::RectF(0.0f, 0.0f, 10, 10), //dest rect
1.0f,
D2D1_BITMAP_INTERPOLATION_MODE::D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR, //effect for scaling
D2D1::RectF(0, 0, 10, 10)); //scource rect
}
};
now, just to test things, I did put a ID2D1Bitmap* bmp; at the start of each method just to see where things got, but the wicdecoder error message just changed to a random place in memory.
Found the issue. the implementation of CoCreateInstance() was fine, but there were a few problems with his code, relating to it being outdated.
NOW, before i begin, i must say, this was PARTLY taken from: https://msdn.microsoft.com/en-us/library/windows/desktop/dd756686(v=vs.85).aspx
the implementation here still gives no usable implementation of CoCreateInstance(), (and also requires you to have the boilerplate code of this tutorial. Also, the tutorial's code is from 2008 and the architecture expands the amount of memory the app uses every time you resize the window... but i digress. main point: DON'T use that tutorial's program example as a model for your own programs, but it does give a good example on how to declare/initialize the proper WIC and D2D objects) the Microsoft documentation for DX12 is also out of date, but this is what I will clarify here.
the correct implementation of CoCreateInstance(), and the correct way to load an image is:
void spritesheet::load(PCWSTR uri, ID2D1HwndRenderTarget * gfx) {
IWICBitmapDecoder *pDecoder = NULL;
IWICBitmapFrameDecode *pSource = NULL;
IWICStream *pStream = NULL;
IWICFormatConverter *pConverter = NULL;
IWICBitmapScaler *pScaler = NULL;
IWICImagingFactory *wicFactory = NULL;
CoCreateInstance(
CLSID_WICImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_IWICImagingFactory,
(LPVOID*)&wicFactory);
HRESULT hr = wicFactory->CreateDecoderFromFilename(
uri,
NULL,
GENERIC_READ,
WICDecodeMetadataCacheOnLoad,
&pDecoder
);
if (SUCCEEDED(hr)) {
// Create the initial frame.
hr = pDecoder->GetFrame(0, &pSource);
}
if (SUCCEEDED(hr)) {
// Convert the image format to 32bppPBGRA
// (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED).
hr = wicFactory->CreateFormatConverter(&pConverter);
}
if (SUCCEEDED(hr)) {
hr = pConverter->Initialize(
pSource,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
NULL,
0.f,
WICBitmapPaletteTypeMedianCut
);
}
if (SUCCEEDED(hr))
{
// Create a Direct2D bitmap from the WIC bitmap.
hr = gfx->CreateBitmapFromWicBitmap(
pConverter,
NULL,
&bmp
);
}
if (pDecoder) {
pDecoder->Release();
}
if (pSource) {
pSource->Release();
}
if (pConverter) {
pConverter->Release();
}
}
Note:
uri simply being the file name, in a PCWSTR format, declared as L"name.bmp" when passing to the function.
the correct way to draw an image is:
void spritesheet::draw(ID2D1HwndRenderTarget * gfx, float bx, float by, float rx, float ry, float dx, float dy) {
D2D1_SIZE_F size = bmp->GetSize();
D2D1_POINT_2F upperLeftCorner = D2D1::Point2F(dx, dy);
gfx->DrawBitmap(
bmp,
D2D1::RectF(
upperLeftCorner.x,
upperLeftCorner.y,
upperLeftCorner.x + rx,
upperLeftCorner.y + ry),
1,
D2D1_BITMAP_INTERPOLATION_MODE::D2D1_BITMAP_INTERPOLATION_MODE_NEAREST_NEIGHBOR,
D2D1::RectF(
bx,
by,
rx,
ry)
);
}
Now, the rest of the D2D documentation is not up to date, but still gives you a good example of what's out there to use. Some of the objects don't exist anymore, like D2D1::Rect being canned and now you only have: D2D1::RectF, nad some of the documentation and tutorials are rather disjointed and untested, but if you dig long enough, you can create a game. just remember to have the x86/x64 redistributeable packages run as part of your installer written in c# (because c++ won't run natively in windows anymore, and c# is half as fast), and your c++ program will run where you need it to.
Im tring to do the solution you gave here but no luck still wicFactory is null.
D2DGauge* d2dg = reinterpret_cast<D2DGauge*>(args);
HRESULT hr;
bmp = nullptr;
IWICBitmapDecoder *pDecoder = NULL;
IWICBitmapFrameDecode *pSource = NULL;
IWICFormatConverter *pConverter = NULL;
//Creating a factory
IWICImagingFactory *wicFactory = NULL;
CoCreateInstance(
CLSID_WICImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_IWICImagingFactory,
(LPVOID*)&wicFactory);
MessageBox(NULL, (LPCWSTR)wicFactory, NULL, MB_OK);
//Creating a decoder
hr = wicFactory->CreateDecoderFromFilename(
filename,
NULL,
GENERIC_READ,
WICDecodeMetadataCacheOnLoad,
&pDecoder);
//Read Frame from image
if (SUCCEEDED(hr)) {
// Create the initial frame.
hr = pDecoder->GetFrame(0, &pSource);
}
//Creating a Converter
if (SUCCEEDED(hr)) {
// Convert the image format to 32bppPBGRA
// (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED).
hr = wicFactory->CreateFormatConverter(&pConverter);
}
//Setup the converter
if (SUCCEEDED(hr)) {
hr = pConverter->Initialize(
pSource,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
NULL,
0.f,
WICBitmapPaletteTypeMedianCut
);
}
//Use the converter to create an D2D1Bitmap
//ID2D1Bitmap* bmp;
if (SUCCEEDED(hr))
{
hr = d2dg->pRT->CreateBitmapFromWicBitmap(
pConverter,
NULL,
&bmp
);
}
if (wicFactory)wicFactory->Release();
if (pDecoder)pDecoder->Release();
if (pConverter)pConverter->Release();
if (pSource)pSource->Release();
How could I make it not a nullptr?

WIC increases the size of TIFF image

Scenario:
Load a TIFF image and extract the frames of tiff image and save it locally.
Combine the extracted frames to the output TIFF image.
When i try to combine the frames, the size of the output tiff image is increasing drastically. For example if my input size if 40 MB , the output is increased to 300 MB.
Below is the code which explains the scenario,
void readTiff()
{
HRESULT hr;
IWICBitmapFrameDecode *frameDecode = NULL;
IWICFormatConverter *formatConverter = NULL;
IWICBitmapEncoder *encoder = NULL;
IWICStream *pOutStream = NULL;
IWICBitmapFrameEncode *frameEncode = NULL;
IWICImagingFactory* m_pWICFactory;
hr = CoCreateInstance(
CLSID_WICImagingFactory,
NULL,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&m_pWICFactory)
);
IWICBitmapDecoder *pIDecoder = NULL;
hr = m_pWICFactory->CreateDecoderFromFilename(
L"D:\\test28\\Multitiff_files\\300dpiTIFF40MB_WATER.tif", // Image to be decoded
NULL, // Do not prefer a particular vendor
GENERIC_READ, // Desired read access to the file
WICDecodeMetadataCacheOnDemand, // Cache metadata when needed
&pIDecoder // Pointer to the decoder
);
UINT frameCount = 0;
pIDecoder->GetFrameCount(&frameCount);
for (int i = 0; i < frameCount; i++)
{
wchar_t temp[200];
int j = i;
swprintf_s(temp, 200, L"D:\\test28\\Multitiff_files\\out\\filename_png%d.jpeg", i);
if (SUCCEEDED(hr))
hr = m_pWICFactory->CreateStream(&pOutStream);
if (SUCCEEDED(hr))
hr = pOutStream->InitializeFromFilename(temp, GENERIC_WRITE);
if (SUCCEEDED(hr))
hr = m_pWICFactory->CreateEncoder(GUID_ContainerFormatJpeg, NULL, &encoder);
if (SUCCEEDED(hr))
hr = encoder->Initialize(pOutStream, WICBitmapEncoderNoCache);
hr = pIDecoder->GetFrame(i, &frameDecode);
if (SUCCEEDED(hr))
hr = m_pWICFactory->CreateFormatConverter(&formatConverter);
hr = formatConverter->Initialize(
frameDecode, // Source frame to convert
GUID_WICPixelFormat8bppIndexed, // The desired pixel format
WICBitmapDitherTypeNone, // The desired dither pattern
NULL, // The desired palette
0.f, // The desired alpha threshold
WICBitmapPaletteTypeMedianCut // Palette translation type
);
IPropertyBag2 *pPropertybag = NULL;
//Create a new frame..
hr = encoder->CreateNewFrame(&frameEncode, &pPropertybag);
//PROPBAG2 option = { 0 };
//option.pstrName = L"ImageQuality";
//VARIANT varValue;
//VariantInit(&varValue);
//varValue.vt = VT_R4;
//varValue.fltVal = 0.01f;
//hr = pPropertybag->Write(
// 1, // number of properties being set
// &option,
// &varValue);
WICPixelFormatGUID pixelFormat;
hr = frameEncode->Initialize(pPropertybag);
//pixelFormat = GUID_WICPixelFormat8bppIndexed;
frameDecode->GetPixelFormat(&pixelFormat);
hr = frameEncode->SetPixelFormat(&pixelFormat);
hr = frameEncode->WriteSource(formatConverter, NULL);
frameEncode->Commit();
encoder->Commit();
if (formatConverter)
formatConverter->Release();
if (frameDecode)
frameDecode->Release();
if (frameEncode)
frameEncode->Release();
if (pOutStream)
pOutStream->Release();
if (encoder)
encoder->Release();
}
if (m_pWICFactory)
m_pWICFactory->Release();
pIDecoder->Release();
}
void combineFile(int count)
{
HRESULT hr;
IWICImagingFactory *pFactory = NULL;
IWICStream *pInStream = NULL;
IWICBitmapDecoder *decoder = NULL;
IWICBitmapFrameDecode *frameDecode = NULL;
IWICFormatConverter *formatConverter = NULL;
IWICBitmapEncoder *encoder = NULL;
IWICStream *pOutStream = NULL;
IWICBitmapFrameEncode *frameEncode = NULL;
hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*)&pFactory);
if (!SUCCEEDED(hr)) {
hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*)&pFactory);
}
if (SUCCEEDED(hr))
hr = pFactory->CreateStream(&pOutStream);
if (SUCCEEDED(hr))
hr = pOutStream->InitializeFromFilename(L"D:\\test28\\Multitiff_files\\out\\out.tiff", GENERIC_WRITE);
if (SUCCEEDED(hr))
hr = pFactory->CreateEncoder(GUID_ContainerFormatWmp, NULL, &encoder);
if (SUCCEEDED(hr))
hr = encoder->Initialize(pOutStream, WICBitmapEncoderNoCache);
for (int i = 0; i < count; i++)
{
wchar_t temp[200];
swprintf_s(temp, 200, L"D:\\test28\\Multitiff_files\\out\\filename_png%d.jpeg", i);
if (SUCCEEDED(hr))
hr = pFactory->CreateStream(&pInStream);
if (SUCCEEDED(hr))
hr = pInStream->InitializeFromFilename(temp, GENERIC_READ);
if (SUCCEEDED(hr))
hr = pFactory->CreateDecoderFromStream(pInStream, NULL, WICDecodeMetadataCacheOnLoad, &decoder);
if (SUCCEEDED(hr))
hr = pFactory->CreateFormatConverter(&formatConverter);
hr = decoder->GetFrame(0, &frameDecode);
//hr = formatConverter->Initialize(
// frameDecode, // Source frame to convert
// GUID_WICPixelFormat8bppIndexed, // The desired pixel format
// WICBitmapDitherTypeNone, // The desired dither pattern
// NULL, // The desired palette
// 0.f, // The desired alpha threshold
// WICBitmapPaletteTypeMedianCut // Palette translation type
// );
WICPixelFormatGUID pixelFormat;
frameDecode->GetPixelFormat(&pixelFormat);
IPropertyBag2 *pPropertybag = NULL;
//Create a new frame..
hr = encoder->CreateNewFrame(&frameEncode, &pPropertybag);
PROPBAG2 option = { 0 };
option.pstrName = L"TiffCompressionMethod";
VARIANT varValue;
VariantInit(&varValue);
varValue.vt = VT_UI1;
varValue.bVal = WICTiffCompressionOption::WICTiffCompressionZIP;
hr = pPropertybag->Write(1, &option, &varValue);
hr = frameEncode->Initialize(pPropertybag);
hr = frameEncode->SetPixelFormat(&pixelFormat);
hr = frameEncode->WriteSource(formatConverter, NULL);
hr = frameEncode->Commit();
if (pInStream)
pInStream->Release();
if (decoder)
decoder->Release();
if (formatConverter)
formatConverter->Release();
if (frameEncode)
frameEncode->Release();
//if (frameDecode)
//frameDecode->Release();
}
encoder->Commit();
if (pFactory)
pFactory->Release();
if (encoder)
encoder->Release();
if (pOutStream)
pOutStream->Release();
}
One easy way to debug this kind of issue is to use ImageMagick which is installed on most Linux distros and is available for OSX and Windows. First use the identify utility within the suite with its verbose option to find out everything about your before and after images like this:
# Find out all we know about first image and put in file "1.txt"
identify -verbose image1.tif > 1.txt
# Find out all we know about second image and put in file "2.txt"
identify -verbose image2.tif > 2.txt
Now use your favourite file comparison tool to see the differences:
opendiff 1.txt 2.txt

Writing IWICBtmap to file - incorrect resolution

I have the following code where I read an image (JPG for test), specify a clipping rectangle area and write the "clipped" area out to a file.
My test image is 320 x 240 pixels # 300dpi. When I read it in all indications say that it is that size but when I write it out the result image is 102 x 76 and looking a the file properties I see no H/V resolution.
Now 320/102 = 3.1372 and 300/96 = 3.125 so is there something with screen resolution vs image?
This entire subject of writing out a IWICBitmap has been a boxing match from the beginning. Why is it this hard?
Thanks a bunch
IWICImagingFactory *pImageFactory = GfxAgent::WICImagingFactory::GetInstance().GetFactory();
D2D1_SIZE_U sizeFrame = D2D1::SizeU(imageRect.Width(), imageRect.Height());
CComPtr<IWICBitmap> pWICBitmap;
hr = pImageFactory->CreateBitmap(imageRect.Width(), imageRect.Height(),
GUID_WICPixelFormat32bppPBGRA,
WICBitmapCacheOnLoad,
&pWICBitmap
);
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;
// define the render target
CComPtr<ID2D1RenderTarget> pRenderTarget = 0;
hr = m_pDirect2dFactory->CreateWicBitmapRenderTarget(pWICBitmap, rtProps, &pRenderTarget);
CComPtr<ID2D1Bitmap> imageS;
hr = GfxAgent::ImageUtilities::LoadImageFromFile(pRenderTarget, m_imgPath, 0, 0, 0, &imageS, &resX, &resY);
if (hr != S_OK)
{
}
// get format of image we just read
D2D1_PIXEL_FORMAT fmt = imageS->GetPixelFormat();
CComPtr<ID2D1Bitmap> imageD;
D2D1_SIZE_U bitmapPixelSize = D2D1::SizeU(imageRect.Width(), imageRect.Height());
// create destination image of "clipped" source image
hr = pRenderTarget->CreateBitmap(bitmapPixelSize, D2D1::BitmapProperties(
D2D1::PixelFormat(fmt.format, fmt.alphaMode),
(float)resX, (float)resY), &imageD);
D2D1_POINT_2U topleft = D2D1::Point2U(0, 0);
D2D1_RECT_U srcRect = D2D1::RectU(imageRect.left, imageRect.top, imageRect.right, imageRect.bottom);
// get the "clipped" source
hr = imageD->CopyFromBitmap(&topleft, imageS, &srcRect);
if (hr != S_OK)
{
}
CComPtr<IWICBitmapEncoder> pEncoder;
CComPtr<IWICBitmapFrameEncode> pFrame;
CComPtr<IWICStream> pStream;
WICPixelFormatGUID format = GUID_WICPixelFormat32bppPBGRA;
// draw the "clipped" image into the render target (WIC image)
if (SUCCEEDED(hr)) {
pRenderTarget->BeginDraw();
pRenderTarget->Clear();
pRenderTarget->DrawBitmap(imageD);
hr = pRenderTarget->EndDraw();
}
// now proceed to write the "clipped" image to a file
if (SUCCEEDED(hr)) {
hr = pImageFactory->CreateStream(&pStream);
}
if (SUCCEEDED(hr)) {
hr = pStream->InitializeFromFilename(MultiByteToUnicode(szNewFileName).c_str(), GENERIC_WRITE);
}
if (SUCCEEDED(hr)) {
hr = pImageFactory->CreateEncoder(GUID_ContainerFormatJpeg, NULL, &pEncoder);
}
if (SUCCEEDED(hr)) {
hr = pEncoder->Initialize(pStream, WICBitmapEncoderNoCache);
}
if (SUCCEEDED(hr)) {
hr = pEncoder->CreateNewFrame(&pFrame, NULL);
}
if (SUCCEEDED(hr)) {
hr = pFrame->Initialize(NULL);
}
if (SUCCEEDED(hr)) {
hr = pFrame->SetSize((UINT)imageD->GetSize().width, (UINT)imageD->GetSize().height);
}
if (SUCCEEDED(hr)) {
hr = pFrame->SetPixelFormat(&format);
}
if (SUCCEEDED(hr)) {
hr = pFrame->WriteSource(pWICBitmap, NULL);
}
if (SUCCEEDED(hr)) {
hr = pFrame->Commit();
}
if (SUCCEEDED(hr)) {
hr = pEncoder->Commit();
}
More info
D2D1_POINT_2U topleft = D2D1::Point2U(0, 0);
D2D1_RECT_U srcRect = D2D1::RectU(imageRect.left, imageRect.top, imageRect.right, imageRect.bottom);
// get the "clipped" source
hr = imageD->CopyFromBitmap(&topleft, imageS, &srcRect);
if (hr != S_OK)
{
}
UINT wD, hD;
wD = (UINT)imageD->GetSize().width;
hD = (UINT)imageD->GetSize().height;
The imageRect is correct LTRB = 0,0,320,240
but after the copy wD = 102 and hD = 76
Why?
Here is some more info
CComPtr<ID2D1Bitmap> imageD;
D2D1_SIZE_U bitmapPixelSize = D2D1::SizeU(imageRect.Width(), imageRect.Height());
// create destination image of "clipped" source image
hr = pRenderTarget->CreateBitmap(bitmapPixelSize, D2D1::BitmapProperties(
D2D1::PixelFormat(fmt.format, fmt.alphaMode),
(float)resX, (float)resY), &imageD);
UINT wD, hD;
wD = (UINT)imageD->GetSize().width;
hD = (UINT)imageD->GetSize().height;
The bitmapPixelSize is correct 320 x 240, resX and Y are 300
format= DXGI_FORMAT_B8G8R8A8_UNORM
alphaMode D2D1_ALPHA_MODE_PREMULTIPLIED
wD = 102 and hD = 76 - Why?
Latest code
IWICImagingFactory *pImageFactory = GfxAgent::WICImagingFactory::GetInstance().GetFactory();
D2D1_SIZE_U sizeFrame = D2D1::SizeU(imageRect.Width(), imageRect.Height());
CComPtr<IWICBitmap> pWICBitmap;
hr = pImageFactory->CreateBitmap(imageRect.Width(), imageRect.Height(),
GUID_WICPixelFormat32bppPBGRA,
WICBitmapCacheOnLoad,
&pWICBitmap
);
// sanity check
UINT wicW, wicH;
pWICBitmap->GetSize(&wicW, &wicH);
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;
// define the render target
CComPtr<ID2D1RenderTarget> pRenderTarget = 0;
hr = m_pDirect2dFactory->CreateWicBitmapRenderTarget(pWICBitmap, rtProps, &pRenderTarget);
CComPtr<ID2D1Bitmap> imageS;
hr = GfxAgent::ImageUtilities::LoadImageFromFile(pRenderTarget, m_imgPath, 0, 0, 0, &imageS, &resX, &resY);
if (hr != S_OK)
{
}
// set new image resolution same as source
pWICBitmap->SetResolution(resX, resY);
// get format of image we just read
D2D1_PIXEL_FORMAT fmt = imageS->GetPixelFormat();
CComPtr<ID2D1Bitmap> imageD;
D2D1_SIZE_U bitmapPixelSize = D2D1::SizeU(imageRect.Width(), imageRect.Height());
// create destination image of "clipped" source image
hr = pRenderTarget->CreateBitmap(bitmapPixelSize, D2D1::BitmapProperties(
D2D1::PixelFormat(fmt.format, fmt.alphaMode),
(float)resX, (float)resY), &imageD);
D2D1_POINT_2U topleft = D2D1::Point2U(0, 0);
D2D1_RECT_U srcRect = D2D1::RectU(imageRect.left, imageRect.top, imageRect.right, imageRect.bottom);
// get the "clipped" source
hr = imageD->CopyFromBitmap(&topleft, imageS, &srcRect);
if (hr != S_OK)
{
}
// just a sanity check (pixels NOT DIPS)
D2D1_SIZE_U sourcePixelSize = imageS->GetPixelSize();
D2D1_SIZE_U destPixelSize = imageD->GetPixelSize();
CComPtr<IWICBitmapEncoder> pEncoder;
CComPtr<IWICBitmapFrameEncode> pFrame;
CComPtr<IWICStream> pStream;
WICPixelFormatGUID format = GUID_WICPixelFormat32bppPBGRA;
// draw the "clipped" image into the render target (WIC image)
if (SUCCEEDED(hr)) {
pRenderTarget->BeginDraw();
pRenderTarget->Clear();
pRenderTarget->DrawBitmap(imageD);
hr = pRenderTarget->EndDraw();
}
// now proceed to write the "clipped" image to a file
if (SUCCEEDED(hr)) {
hr = pImageFactory->CreateStream(&pStream);
}
if (SUCCEEDED(hr)) {
hr = pStream->InitializeFromFilename(MultiByteToUnicode(szNewFileName).c_str(), GENERIC_WRITE);
}
if (SUCCEEDED(hr)) {
hr = pImageFactory->CreateEncoder(GUID_ContainerFormatJpeg, NULL, &pEncoder);
}
if (SUCCEEDED(hr)) {
hr = pEncoder->Initialize(pStream, WICBitmapEncoderNoCache);
}
if (SUCCEEDED(hr)) {
hr = pEncoder->CreateNewFrame(&pFrame, NULL);
}
if (SUCCEEDED(hr)) {
hr = pFrame->Initialize(NULL);
}
if (SUCCEEDED(hr)) {
hr = pFrame->SetSize(destPixelSize.width, destPixelSize.height);
}
if (SUCCEEDED(hr)) {
hr = pFrame->SetPixelFormat(&format);
}
if (SUCCEEDED(hr)) {
hr = pFrame->WriteSource(pWICBitmap, NULL);
}
if (SUCCEEDED(hr)) {
hr = pFrame->Commit();
}
if (SUCCEEDED(hr)) {
hr = pEncoder->Commit();
}
ID2D1Bitmap::GetSize gets you DIPs:
Returns the size, in device-independent pixels (DIPs), of the bitmap.
A DIP is 1/96 of an inch. To retrieve the size in device pixels, use the ID2D1Bitmap::GetPixelSize method.
In your case the size is 320 px * 96 dpi/px / 300 dpi = 102.4 device-independent pixels. The same along Y axis.
Knowing what the original image's resolution is when I create the render target from the WICBitmap I used the following properties
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;
rtProps.dpiX = (float)m_img.GetResolutionX();
rtProps.dpiY = (float)m_img.GetResolutionY();
the key was using the resolution of the original image in the create, attempting to set them later did nothing. Roman gave me the "hint" - Thanks

Direct2D ID2D1RenderTarget::CreateBitmapFromWicBitmap fails with no error

I just try to add LoadBitmapFromFile function from sample (from SDK) to my MFC project. So my app fails during runtime on line, no errors, no warnings.
hr = pRenderTarget->CreateBitmapFromWicBitmap(pConverter, NULL, ppBitmap);
When I debugging it and goes over this line I receive empty window and debug session stops. How to find out what the error is? What could be the cause?
HRESULT DemoApp::LoadBitmapFromFile(
ID2D1RenderTarget *pRenderTarget,
IWICImagingFactory *pIWICFactory,
PCWSTR uri,
UINT destinationWidth,
UINT destinationHeight,
ID2D1Bitmap **ppBitmap)
{
HRESULT hr = S_OK;
IWICBitmapDecoder *pDecoder = NULL;
IWICBitmapFrameDecode *pSource = NULL;
IWICStream *pStream = NULL;
IWICFormatConverter *pConverter = NULL;
IWICBitmapScaler *pScaler = NULL;
hr = pIWICFactory->CreateDecoderFromFilename(
uri,
NULL,
GENERIC_READ,
WICDecodeMetadataCacheOnLoad,
&pDecoder
);
if (SUCCEEDED(hr))
{
// Create the initial frame.
hr = pDecoder->GetFrame(0, &pSource);
}
if (SUCCEEDED(hr))
{
// Convert the image format to 32bppPBGRA
// (DXGI_FORMAT_B8G8R8A8_UNORM + D2D1_ALPHA_MODE_PREMULTIPLIED).
hr = pIWICFactory->CreateFormatConverter(&pConverter);
}
if (SUCCEEDED(hr))
{
// If a new width or height was specified, create an
// IWICBitmapScaler and use it to resize the image.
if (destinationWidth != 0 || destinationHeight != 0)
{
UINT originalWidth, originalHeight;
hr = pSource->GetSize(&originalWidth, &originalHeight);
if (SUCCEEDED(hr))
{
if (destinationWidth == 0)
{
FLOAT scalar = static_cast<FLOAT>(destinationHeight) / static_cast<FLOAT>(originalHeight);
destinationWidth = static_cast<UINT>(scalar * static_cast<FLOAT>(originalWidth));
}
else if (destinationHeight == 0)
{
FLOAT scalar = static_cast<FLOAT>(destinationWidth) / static_cast<FLOAT>(originalWidth);
destinationHeight = static_cast<UINT>(scalar * static_cast<FLOAT>(originalHeight));
}
hr = pIWICFactory->CreateBitmapScaler(&pScaler);
if (SUCCEEDED(hr))
{
hr = pScaler->Initialize(
pSource,
destinationWidth,
destinationHeight,
WICBitmapInterpolationModeCubic
);
}
if (SUCCEEDED(hr))
{
hr = pConverter->Initialize(
pScaler,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
NULL,
0.f,
WICBitmapPaletteTypeMedianCut
);
}
}
}
else // Don't scale the image.
{
hr = pConverter->Initialize(
pSource,
GUID_WICPixelFormat32bppPBGRA,
WICBitmapDitherTypeNone,
NULL,
0.f,
WICBitmapPaletteTypeMedianCut
);
}
}
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;
}