[英]how to draw pixels to pf1bit in Delphi?
How to draw pixels to a TImage but in pf1bit bitmap format? 如何将像素绘制到TImage但是采用pf1bit位图格式? 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. 请注意,图像大小为320x240像素。
Thanks before. 谢谢你。
You need to pack 8 pixels into a single byte for 1 bit color format. 对于1位颜色格式,您需要将8个像素打包到单个字节中。 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: 输出如下所示:
Update 更新
Rob's comment prompted me to look at using Pixels[]
rather than the bit-twiddling above. Rob的评论促使我看看使用
Pixels[]
而不是上面的比特。 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. 由于每次调用分配
Pixels[]
导致调用Windows API函数SetPixel
,因此比特错误的代码会表现得更好。 Of course, that would only ever matter if your bitmap creation code was a performance hot-spot. 当然,只有你的位图创建代码是一个性能热点才会有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.