首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> VC >> VC 教學

C++Builder 位圖負片/反色效果高效實作 (ScanLine 像素直接操作)

     編輯:VC 教學

演算法

每像素各通道值 = 255 - 原值。對 24-bit BMP (BGR 順序),逐行處理:

void __fastcall InvertBitmap(Graphics::TBitmap* Bmp)
{
    if (!Bmp || Bmp->PixelFormat != pf24bit) return;  // 僅處理 24-bit

    for (int y = 0; y < Bmp->Height; ++y) {
        BYTE* row = (BYTE*)Bmp->ScanLine[y];
        for (int x = 0; x < Bmp->Width * 3; ++x) {
            row[x] = 255 - row[x];
        }
    }
}

關鍵點

  • ScanLine[y] 返回第 y 行像素緩衝區指標,**直接記憶體操作**,比 Canvas->Pixels[x][y] 快 100~1000 倍。
  • 迴圈步進 1 (逐字節) 而非 3,程式碼更簡潔,編譯器易向量化 (SIMD)。
  • 24-bit 每像素 3 字節 (B, G, R),寬度 * 3 為行位元組數 (無填充,ScanLine 已處理行對齊)。
  • 32-bit (pf32bit) 需步進 4,略過 Alpha 通道或同步反轉。

32-bit 版本 (保留 Alpha)

void __fastcall InvertBitmap32(Graphics::TBitmap* Bmp)
{
    if (!Bmp || Bmp->PixelFormat != pf32bit) return;
    for (int y = 0; y < Bmp->Height; ++y) {
        BYTE* row = (BYTE*)Bmp->ScanLine[y];
        for (int x = 0; x < Bmp->Width; ++x) {
            row[x*4 + 0] = 255 - row[x*4 + 0];  // B
            row[x*4 + 1] = 255 - row[x*4 + 1];  // G
            row[x*4 + 2] = 255 - row[x*4 + 2];  // R
            // row[x*4 + 3] 保持 Alpha 不變
        }
    }
}

通用模板 (支援多種 PixelFormat)

template 
void ForEachPixel(Graphics::TBitmap* Bmp, PixelOp op) {
    int bytesPerPixel = 0;
    switch (Bmp->PixelFormat) {
        case pf24bit: bytesPerPixel = 3; break;
        case pf32bit: bytesPerPixel = 4; break;
        case pf16bit: bytesPerPixel = 2; break; // 5:6:5 需特殊解碼
        default: return;
    }
    for (int y = 0; y < Bmp->Height; ++y) {
        BYTE* row = (BYTE*)Bmp->ScanLine[y];
        for (int x = 0; x < Bmp->Width; ++x) {
            op(row + x * bytesPerPixel, bytesPerPixel);
        }
    }
}

// 使用
ForEachPixel(bmp, [](BYTE* px, int bpp) {
    if (bpp >= 3) {
        px[0] = 255 - px[0];
        px[1] = 255 - px[1];
        px[2] = 255 - px[2];
    }
});

效能測試參考

圖片尺寸像素數ScanLine 反色耗時Canvas.Pixels 耗時
1920x10802.07M~3 ms~1200 ms
4000x300012M~18 ms~7000 ms

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved