7

我正在寻找如何使用 GDI(不是 GDI+)将 32 位位图转换为灰度的简单解决方案。是否有可能通过更改位图的调色板或其他方式?

当然,在 Delphi 中有很多像这样的例子,但我正在寻找一个 WinAPI 函数,它可以在没有迭代的情况下做到这一点。

4

2 回答 2

9

我还没有发现任何单一的 GDI 函数可以做到这一点。正如大卫在他的评论中提到的,最简单的方法是扫描每一行并计算像素颜色。您正在寻找的可能是luminance公式。

这个公式的变化很少,在下面的例子中,我使用了 推荐的那个ITU,请参阅this document第 2.5.1 节。正如我在某处发现的那样,这个公式甚至被众所周知的 Adob​​e Photoshop 使用。以下代码示例支持并仅期望 24 位像素格式位图作为输入:

procedure BitmapGrayscale(ABitmap: TBitmap);
type
  PPixelRec = ^TPixelRec;
  TPixelRec = packed record
    B: Byte;
    G: Byte;
    R: Byte;
  end;
var
  X: Integer;
  Y: Integer;
  Gray: Byte;
  Pixel: PPixelRec;
begin
  for Y := 0 to ABitmap.Height - 1 do
  begin
    Pixel := ABitmap.ScanLine[Y];
    for X := 0 to ABitmap.Width - 1 do
    begin
      Gray := Round((0.299 * Pixel.R) + (0.587 * Pixel.G) + (0.114 * Pixel.B));
      Pixel.R := Gray;
      Pixel.G := Gray;
      Pixel.B := Gray;
      Inc(Pixel);
    end;
  end;
end;
于 2011-12-19T12:45:13.390 回答
5

您可以创建调色板 DIB 部分,每像素 8 位和 256 种颜色,并将调色板初始化为灰色阴影 { 0, 0, 0 }, { 1, 1, 1 }, ... { 255, 255, 255 }。

进入此位图的单个 GDIBitBlt将使您的原始图像变灰。这是代码片段(在 C++、ATL 和 WTL 中 - 但你应该明白)。

CWindowDC DesktopDc(NULL);
CDC BitmapDc;
ATLVERIFY(BitmapDc.CreateCompatibleDC(DesktopDc));
CBitmap Bitmap;
CTempBuffer<BITMAPINFO> pBitmapInfo;
const SIZE_T nBitmapInfoSize = sizeof (BITMAPINFO) + 256 * sizeof (RGBQUAD);
pBitmapInfo.AllocateBytes(nBitmapInfoSize);
ZeroMemory(pBitmapInfo, nBitmapInfoSize);
pBitmapInfo->bmiHeader.biSize = sizeof pBitmapInfo->bmiHeader;
pBitmapInfo->bmiHeader.biWidth = 320;
pBitmapInfo->bmiHeader.biHeight = 240;
pBitmapInfo->bmiHeader.biPlanes = 1;
pBitmapInfo->bmiHeader.biBitCount = 8;
pBitmapInfo->bmiHeader.biCompression = BI_RGB;
pBitmapInfo->bmiHeader.biSizeImage = 240 * 320;
pBitmapInfo->bmiHeader.biClrUsed = 256;
pBitmapInfo->bmiHeader.biClrImportant = 256;
for(SIZE_T nIndex = 0; nIndex < 256; nIndex++)
{
    pBitmapInfo->bmiColors[nIndex].rgbRed = (BYTE) nIndex;
    pBitmapInfo->bmiColors[nIndex].rgbGreen = (BYTE) nIndex;
    pBitmapInfo->bmiColors[nIndex].rgbBlue = (BYTE) nIndex;
}
Bitmap.Attach(CreateDIBSection(DesktopDc, pBitmapInfo, 0, DIB_RGB_COLORS, NULL, 0));
ATLVERIFY(Bitmap);
BitmapDc.SelectBitmap(Bitmap);
////////////////////////////////////////////////
// This is what greys it out:
ATLVERIFY(BitBlt(BitmapDc, 0, 0, 320, 240, DesktopDc, 0, 0, SRCCOPY));
////////////////////////////////////////////////
ATLVERIFY(BitBlt(DesktopDc, 0, 240, 320, 240, BitmapDc, 0, 0, SRCCOPY));
于 2011-12-19T22:57:31.320 回答