3

ピクセルを 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;

画像サイズは 320x240 ピクセルであることに注意してください。

前にありがとう。

4

1 に答える 1

7

1 ビット カラー形式では、8 ピクセルを 1 バイトにパックする必要があります。内側のループは次のようになります。

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;

出力は次のようになります。

ここに画像の説明を入力

アップデート

Rob のコメントは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;

assign を呼び出すたびPixels[]に Windows API function が呼び出されるためSetPixel、ビットをいじるコードのパフォーマンスが向上します。もちろん、それが問題になるのは、ビットマップ作成コードがパフォーマンスのホット スポットである場合だけです。

于 2012-07-07T13:54:11.990 に答える