How to covert IWICBitmapSource to HBITMAP? - c++

It's easy to produce IWICBitmap from HBITMAP with CreateBitmapFromHBITMAP factory method. But how to get simple GDI bitmap from IWICBitmapSource?

Unfortulately there is no way to convert a IWICBitmap to a HBITMAP, or to get one from a IWICBitmapSource. You could, however, easily create the HBITMAP from a pixel buffer if the format is compatible with what CreateBitmap expects.
Assuming a 32-bit RGBA bitmap:
IWICBitmapSource *bitmap_source = some_func();
UINT width = 0, height = 0;
bitmap_source->GetSize(&width, &height);
std::vector<BYTE> buffer(width * height * 4);
bitmap_source->CopyPixels(0, width * 4, buffer.size(), buffer.data());
HBITMAP bitmap = CreateBitmap(width, height, 1, 32, buffer.data());

There's no guarantee that behind the scenes IWICBitmapSource even uses a GDI bitmap. You can access the raw bits using the IWICBitmap::Lock method, but if you want to use the bitmap with GDI functions I think you will need to create a GDI bitmap and copy the bits to it yourself.

Related

Read pixels (raw bytes) from an hbitmap without copying?

I have an HBITMAP handle to a device-dependent bitmap, resulting from this code:
// copy screen to bitmap
HDC hScreen = GetDC(NULL);//don't use hwnd, it doesn't work for non native windows
HDC hDC = CreateCompatibleDC(hScreen);
HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, w, h);
HGDIOBJ old_obj = SelectObject(hDC, hBitmap);
BOOL bRet = BitBlt(hDC, 0, 0, w, h, hScreen, x1, y1, SRCCOPY);
I want to access (read-only) the bits of the bitmap, read some values, do some calculations, then discard it.
According to this answer, I shouldn't use GetDIBits() or GetBitmapBits() since they copy the data, but instead I should use:
BITMAP bitmap;
GetObject(hBitmap, sizeof(bitmap), (LPVOID)&bitmap);
But according to GetObject's documentation:
If hgdiobj is a handle to a bitmap created by calling CreateDIBSection, and the specified buffer is large enough, the GetObject function returns a DIBSECTION structure. In addition, the bmBits member of the BITMAP structure contained within the DIBSECTION will contain a pointer to the bitmap's bit values.
If hgdiobj is a handle to a bitmap created by any other means, GetObject returns only the width, height, and color format information of the bitmap. You can obtain the bitmap's bit values by calling the GetDIBits or GetBitmapBits function.
Which is pointed to in a comment on the above answer:
According to this https://msdn.microsoft.com/en-us/library/dd144904(v=vs.85).aspx if bitmap is not created by CreateDIBSection bitmap.bmBit pointer will be null.
So, is there anyway to access the bits of the bitmap (RGB values), without copying them?
If it helps, the device on which the bitmap is dependent is always a screen, so I guess it's always a 24bit or 32bit bitmap.
In this article, regarding how to save an HBITMAP to a file, there's this section:
// Allocate memory for the BITMAPINFO structure. (This structure
// contains a BITMAPINFOHEADER structure and an array of RGBQUAD
// data structures.)
if (cClrBits < 24) pbmi = (PBITMAPINFO)LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * (1 << cClrBits));
// There is no RGBQUAD array for these formats: 24-bit-per-pixel or 32-bit-per-pixel
else pbmi = (PBITMAPINFO)LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER));
So, I don't really understand what's happening here, and which is right?

Rotating a CImage and preserving its alpha/transparency channel

I have some existing code that uses a CImage which has an alpha channel, and I need to rotate it.
I have found the following suggestion which converts the CImage to a GDI+ Bitmap and then rotates it, and the rotated result ends up back in the CImage.
Bitmap* gdiPlusBitmap=Bitmap::FromHBITMAP(atlBitmap.Detach());
gdiPlusBitmap->RotateFlip(Rotate90FlipNone);
HBITMAP hbmp;
gdiPlusBitmap->GetHBITMAP(Color::White, &hbmp);
atlBitmap.Attach(hbmp);
Apparently it works without actually copying the bitmap bytes, which is great, but the problem is that if you create a Bitmap object from a HBITMAP it throws away the alpha channel.
Apparently to preserve the alpha channel you must instead create the Bitmap using the constructor
Bitmap(
[in] INT width,
[in] INT height,
[in] INT stride,
[in] PixelFormat format,
[in] BYTE *scan0
);
So I'm trying to adapt the above to use this constructor, but the interaction between CImage and Bitmap is a bit confusing. I think I need to create the Bitmap like this
Bitmap* gdiPlusBitmap = new Bitmap(
pCImage->GetWidth(),
pCImage->GetHeight(),
pCImage->GetPitch(),
PixelFormat32bppARGB,
(BYTE *)pCImage->GetBits());
nGDIStatus = gdiPlusBitmap->RotateFlip(Rotate90FlipNone);
but I'm not sure how to make the CImage pick up the changes (so that I end up with the original CImage rotated), or where to delete the Bitmap object.
Does anyone know the correct way to do this, preserving the alpha channel ?
Ideally I'd like to avoid copying the bitmap data, but it's not mandatory.
You can use Gdiplus::Graphics to draw bitmap on CImage.
Note, hard coding PixelFormat32bppARGB can cause problems if image doesn't support alpha channel. I added some basic error check.
CImage image;
if (S_OK != image.Load(L"c:\\test\\test.png"))
{
AfxMessageBox(L"can't open");
return 0;
}
int bpp = image.GetBPP();
//get pixel format:
HBITMAP hbmp = image.Detach();
Gdiplus::Bitmap* bmpTemp = Gdiplus::Bitmap::FromHBITMAP(hbmp, 0);
Gdiplus::PixelFormat pixel_format = bmpTemp->GetPixelFormat();
if (bpp == 32)
pixel_format = PixelFormat32bppARGB;
image.Attach(hbmp);
//rotate:
Gdiplus::Bitmap bmp(image.GetWidth(), image.GetHeight(), image.GetPitch(), pixel_format, static_cast<BYTE*>(image.GetBits()));
bmp.RotateFlip(Gdiplus::Rotate90FlipNone);
//convert back to image:
image.Destroy();
if (image.Create(bmp.GetWidth(), bmp.GetHeight(), 32, CImage::createAlphaChannel))
{
Gdiplus::Bitmap dst(image.GetWidth(), image.GetHeight(), image.GetPitch(), PixelFormat32bppARGB, static_cast<BYTE*>(image.GetBits()));
Gdiplus::Graphics graphics(&dst);
graphics.DrawImage(&bmp, 0, 0);
}

Editing bitmap in memory using C++

I have a two dimensional array of data that I want to display as an image.
The plan goes something like this -
Create a bitmap using CreateCompatibleBitmap (this results in a solid black bitmap and I can display this with no problems)
Edit the pixels of this bitmap to match my data
BitBlt the bitmap to the window
I think that I need a pointer to the place in memory where the pixel data begins. I've tried many different methods of doing this and googled it for 3 days and still haven't been able to even edit a single pixel.
Using a loop of SetPixel(HDC, x, y, Color) to set each pixel works but VERY slowly.
I have accomplished this in C# by locking the bitmap and editing the bits, but I am new to C++ and can't seem to figure out how to do something similar.
I have mostly been trying to use memset(p, value, length)
For "p" I have tried using the handle returned from CreateCompatibleBitmap, the DC for the bitmap, and the DC for the window. I have tried all sorts of values for the value and length.
I'm not sure if this is the right thing to use though.
I don't have to use a bitmap, that's just the only thing I know to do. Actually it would be awesome to find a way to directly change the main window's DC.
I do want to avoid libraries though. I am doing this purely for learning C++.
This took QUITE a bit of research so I'll post exactly how it is done for anyone else who may be looking.
This colors every pixel red.
hDC = BeginPaint(hWnd, &Ps);
const int
width = 400,
height = 400,
size = width * height * 3;
byte * data;
data = new byte[size];
for (int i = 0; i < size; i += 3)
{
data[i] = 0;
data[i + 1] = 0;
data[i + 2] = 255;
}
BITMAPINFOHEADER bmih;
bmih.biBitCount = 24;
bmih.biClrImportant = 0;
bmih.biClrUsed = 0;
bmih.biCompression = BI_RGB;
bmih.biWidth = width;
bmih.biHeight = height;
bmih.biPlanes = 1;
bmih.biSize = 40;
bmih.biSizeImage = size;
BITMAPINFO bmpi;
bmpi.bmiHeader = bmih;
SetDIBitsToDevice(hDC, 0, 0, width, height, 0, 0, 0, height, data, &bmpi, DIB_RGB_COLORS);
delete[] data;
memset can be used on the actually RGB information array (but you need to also know the format of the bitmap, if a pixel has 32 or 24 bits ).
From a bit of research on msdn, it seems that what you want to get is the BITMAP structure :
http://msdn.microsoft.com/en-us/library/k1sf4cx2.aspx
There you have the bmBits on which you can memset.
How to get there from your function ?
Well, CreateCompatibleBitmap returns a HBITMAP structure and it seems you can get BITMAP from HBITMAP with the following code :
BITMAP bmp;
GetObject(hBmp, sizeof(BITMAP), &bmp);
This however seems to get a you copy of the existing bitmap info, which only solves your memset problem (you can now set the bitmap information with memset, eventhou I don't see any other use for memeset besides making the bmp all white or black).
There should be a function that allows you to set the DC bites to a bitmap thou, so you should be able to use the new bitmap as a parameter.

Create a HBITMAP which points to an existing memory buffer

I am using the FreeImage library to store and manipulate bitmap data. Part of my code requires me to take a screenshot of a window (in Windows), and store it as a FBITMAP* (FreeImage's bitmap data structure). The method I have worked out of doing this involves two steps: capture the image, then convert it to a FBITMAP*.
To capture the image, I do something like this:
HWND window; // Assume this is a valid handle to my window
int width; // width of window client area
int height; // height of window client area
HDC windowDC = GetDC(window);
HDC captureDC = CreateCompatibleDC(windowDC);
HBITMAP screenshot = CreateCompatibleBitmap(windowDC, width, height);
SelectObject(captureDC, screenshot);
BitBlt(captureDC, 0, 0, width, height,
captureDC, 0, 0, SRCCOPY|CAPTUREBLT);
ReleaseDC(window, windowDC);
DeleteDC(captureDC);
FreeImage provides a function which returns a raw pointer to the pixel data:
BYTE* FreeImage_GetBits(FBITMAP*)
The FAQ explains that a HBITMAP (WinAPI handle to a bitmap) can be converted to a FBITMAP* using GetDIBits, which takes a source HBITMAP and a destination raw pointer as arguments, and copies the pixel data from one to the other.
The problem with this approach is that I have copied the data twice - once in the BitBlt from the window DC to the HBITMAP selected in the memory DC, and then again from the HBITMAP to the FreeImage memory buffer. I wish to remove this inefficiency and copy the data directly to my raw pointer in the BitBlt operation. For this to work, I need a memory DC which has a HBITMAP selected into it, and where that HBITMAP points to my memory buffer instead of to memory that Windows allocated for it.
How can I achieve this?

Display 32bit bitmap - Palette

I have an image data in a buffer(type - long) from a scanner which is 32 bit.
For example, buffer[0]'s corresponding pixel value is 952 which is [184, 3, 0, 0] <-[R,G,B,A];
I want to display/Paint/draw on to the screen; I am confused when i tried to read about displying bitmaps. I looked at win32 functions, CBitmap class, windows forms (picture box) etc I am hard to understand the general idea/appraoch for displaying this buffer data on to a application window.
I have constructed the BITMAPFILEHEADER AND BITMAPINFOHEADER; Has the pixel data in a buffer, (unsigned char *)vInBuff whose size is vImageSz;
//construct the BMP file Header
vBmfh.bfType = 19778;
vBmfh.bfSize = 54+vImageSz;//size of the whole image
vBmfh.bfReserved2 = 0;
vBmfh.bfReserved1 = 0;
vBmfh.bfOffBits = 54;//offset from where the pixel data can be found
//Construct the BMP info header
vBmih.biSize = 40;//size of header from this point
vBmih.biWidth = 1004;
vBmih.biHeight = 1002;
vBmih.biPlanes = 1;
vBmih.biCompression = BI_RGB;
vBmih.biSizeImage = vBmih.biWidth*vBmih.biHeight*4;
vBmih.biBitCount = 32;
vBmih.biClrUsed = 0;
vBmih.biClrUsed = 0;
1.What is that i should be doing next to display this?
2 What should i be using to display the 32bit bitmap? I see people using createwindows functions, windows forms, MFC etc;
3.I also understand that BitBlt,createDIBSection, OnPaint etc are being used? I am confused by these various functions and coding platforms? Please suggest me a simple approach.
4.How can i create a palette to display a 32 bit image?
Thanks
Raj
EDITED TRYING TO IMPLEMENT DAVE'S APPROACH, CAN SOMEBODY COMMENT ON MY IMPLEMTATION. I couldn't continue to the bitblt as i donot have two HDC, i donot know how to get this one? Any help please
DisplayDataToImageOnScreen(unsigned char* vInBuff, int vImageSz) // buffer with pixel data, Size of pixel data
{
unsigned char* vImageBuff = NULL;
HDC hdcMem=CreateCompatibleDC(NULL);
HBITMAP hBitmap = CreateDIBSection(hdcMem,
(BITMAPINFO*)&vBmih,
DIB_RGB_COLORS,
(void **)&vImageBuff,
NULL, 0);
GetDIBits(hdcMem,
hBitmap,
0,
1,
(void**)&vImageBuff,
(BITMAPINFO*)&vBmih,
DIB_RGB_COLORS);
memcpy(vImageBuff,vInBuff,vImageSz);
}
An alternative if you just want to plot it on screen is to use TinyPTC ( http://sourceforge.net/projects/tinyptc/files/ ). It's just 3 functions and very simple if you just want to plot some pixels.
EDIT: Seems like http://www.pixeltoaster.com is a continuation of TinyPTC, probably preffered.
If you have image's bytes already in a buffer you can use:
a CBitmap object (MFC) and the method CBitmap::CreateBitmapIndirect
or
win32 routine CreateBitmapIndirect.
Now you can use BitBlt to draw it on a DC. To get a window DC use GetDC.
There is no need to create a pallete for 32 bit images.
Here's a simplified approach you can try, broken down into steps:
BITMAPINFO bitmapinfo = { 0 };
bitmapinfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bitmapinfo.bmiHeader.biWidth = 1004;
bitmapinfo.bmiHeader.biHeight = -1002;
bitmapinfo.bmiHeader.biPlanes = 1;
bitmapinfo.bmiHeader.biCompression = BI_RGB;
HBITMAP hBitmap = CreateDIBSection(NULL,
&bitmapinfo,
DIB_RGB_COLORS,
(void **)&vImageBuff,
NULL,
0);
Now party on vImageBuff and then cache hBitmap somewhere so that within your wndproc you can then in the WM_PAINT handler:
select hBitmap into temp compatible HDC
call BitBlt(..., SRCCOPY) from the compatible HDC to the window's HDC. the other parameters should be obvious. don't try to stretch or do anything fancy at first.
remember to select the original dummy bitmap into the temp HDC before destroying it.
If you aren't seeing results try looping through vImageBuff and just set every pixel to RGB(255, 0, 0), or something like that, just to sanity check the rest of the logic.
If nothing is drawing make sure that the alpha component for each pixel is 255.
If you're getting a garbled image then you need to double-check pixelformat, stride, etc.
Here's a strategy you might like:
Create a bitmap with the same size as your scanned data, and the same format (use CreateDIBSection).
Use GetDIBits to get the base address of the pixel data.
Copy your data (from the scanner) to the address GetDIBits returns.
Now render your bitmap! (use BitBlt, or somesuch).
Regarding palettes- a 32bit image does not, generally, have an explicit palette - you'd need 16.7million (assuming 8bits of alpha) values in the palette. Generally the palette is assumed to be 8bits red, 8bits green, 8bits blue, as you've described above.