如何在Delphi中将像素绘制到pf1bit?

use*_*396 3 delphi image

如何将像素绘制到TImage但是采用pf1bit位图格式?我试过但结果是整个图像都是黑色的.

这是我试过的代码:

image1.picture.bitmap.loadfromfile('example.bmp'); // an image which is RGB pf24bit with 320 x 240 px resolution
image1.picture.bitmap.pixelformat := pf1bit;
for i:=0 to round(image1.picture.bitmap.canvas.height/2) - 1 do
  begin
    for j:=0 to round(image1.picture.bitmap.canvas.width/2) - 1 do
      begin
        image1.picture.bitmap.Canvas.pixels[i,j]:=1; // is this correct? ... := 1? I've tried to set it to 255 (mean white), but still get black 
      end;
  end;
Run Code Online (Sandbox Code Playgroud)

请注意,图像大小为320x240像素.

谢谢你.

Dav*_*nan 6

对于1位颜色格式,您需要将8个像素打包到单个字节中.内部循环看起来像这样:

var
  bm: TBitmap;
  i, j: Integer;
  dest: ^Byte;
  b: Byte;
  bitsSet: Integer;
begin
  bm := TBitmap.Create;
  Try
    bm.PixelFormat := pf1bit;
    bm.SetSize(63, 30);
    for i := 0 to bm.Height-1 do begin
      b := 0;
      bitsSet := 0;
      dest := bm.Scanline[i];
      for j := 0 to bm.Width-1 do begin
        b := b shl 1;
        if odd(i+j) then
          b := b or 1;
        inc(bitsSet);
        if bitsSet=8 then begin
          dest^ := b;
          inc(dest);
          b := 0;
          bitsSet := 0;
        end;
      end;
      if b<>0 then
        dest^ := b shl (8-bitsSet);
    end;
    bm.SaveToFile('c:\desktop\out.bmp');
  Finally
    bm.Free;
  End;
end;
Run Code Online (Sandbox Code Playgroud)

输出如下所示:

在此输入图像描述

更新

罗伯的评论促使我看到使用Pixels[]而不是上面的比特.事实上,这是完全可能的.

var
  bm: TBitmap;
  i, j: Integer;
  Color: TColor;
begin
  bm := TBitmap.Create;
  Try
    bm.PixelFormat := pf1bit;
    bm.SetSize(63, 30);
    for i := 0 to bm.Height-1 do begin
      for j := 0 to bm.Width-1 do begin
        if odd(i+j) then begin
          Color := clBlack;
        end else begin
          Color := clWhite;
        end;
        bm.Canvas.Pixels[j,i] := Color;
      end;
    end;
    bm.SaveToFile('c:\desktop\out.bmp');
  Finally
    bm.Free;
  End;
end;
Run Code Online (Sandbox Code Playgroud)

由于每次调用assign都会Pixels[]导致调用Windows API函数SetPixel,因此bit-twiddling代码的性能会更好.当然,只有你的位图创建代码是一个性能热点才会有用.