3

How to draw pixels to a TImage but in pf1bit bitmap format? I have tried but the result is the whole of the image are black.

here is the code I've tried :

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;

note that the image size is 320x240 pixel.

Thanks before.

4

1 回答 1

7

You need to pack 8 pixels into a single byte for 1 bit color format. The inner loop would look like this:

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;

The output looks like this:

enter image description here

Update

Rob's comment prompted me to look at using Pixels[] rather than the bit-twiddling above. And indeed it is perfectly possible.

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;

Since each call to assign Pixels[] results in a call to the Windows API function SetPixel, the bit-twiddling code would perform better. Of course, that would only ever matter if your bitmap creation code was a performance hot-spot.

于 2012-07-07T13:54:11.990 回答