#include <windows.h>
// 将位图变灰色的函数
void MakeBitmapGrayscale(HBITMAP hBitmap) {
BITMAP bm;
GetObject(hBitmap, sizeof(BITMAP), &bm);
int width = bm.bmWidth;
int height = bm.bmHeight;
int lineBytes = bm.bmWidthBytes;
BYTE *pixels = new BYTE[lineBytes * height];
HDC hDC = GetDC(NULL);
HDC hMemDc = CreateCompatibleDC(hDC);
HBITMAP hOldBitmap = (HBITMAP)SelectObject(hMemDc, hBitmap);
GetBitmapBits(hBitmap, lineBytes * height, pixels);
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
BYTE *pixel = pixels + i * lineBytes + j * 4;
// 计算灰色值
BYTE gray = (pixel[2] + pixel[1] + pixel[0]) / 3;
// 设置RGB通道的值为灰色值
pixel[0] = gray;
pixel[1] = gray;
pixel[2] = gray;
}
}
SetBitmapBits(hBitmap, lineBytes * height, pixels);
SelectObject(hMemDc, hOldBitmap);
DeleteDC(hMemDc);
ReleaseDC(NULL, hDC);
delete[] pixels;
}