将具有任何像素格式的位图转换为特定像素格式

时间:2015-04-09 08:42:28

标签: delphi bitmap delphi-xe2

我正在尝试将一堆图像转换为可能具有任何像素格式(4位,8位,16位,24位等)到1位的图像。

我有以下代码将24位转换为1位,但这不处理任何其他像素格式。

procedure TFormMain.ButtonConvertClick(Sender: TObject);
var
  Bitmap: TBitmap;
  NewBitmap: TBitmap;
  x,y: Integer;
  ScanLine: pRGBTriple;
  Colour: Integer;
  FilePath: String;
  FileName: String;
begin
  Bitmap := TBitmap.Create;
  try
    Bitmap.LoadFromFile(EditFileName.Text);
    NewBitmap := TBitmap.Create;
    try
      NewBitmap.PixelFormat := pf1bit;
      NewBitmap.Height := Bitmap.Height;
      NewBitmap.Width := Bitmap.Width;
      for y := 0 to Bitmap.Height -1 do
        begin
          ScanLine := Bitmap.ScanLine[y];
          for x := 0 to Bitmap.Width -1 do
            begin
              Colour := (ScanLine.rgbtBlue + ScanLine.rgbtGreen + ScanLine.rgbtRed) div 3;
              if (Colour >= 128)
                then Colour := clWhite
                else Colour := clBlack;
              NewBitmap.Canvas.Pixels[x, y] := Colour;
              Inc(ScanLine);
            end;
        end;
      FilePath := ExtractFilePath(EditFileName.Text);
      FileName := TPath.GetFileNameWithoutExtension(EditFileName.Text);
      NewBitmap.SaveToFile(TPath.Combine(FilePath, FileName + '-copy.bmp'));
    finally
      FreeAndNil(NewBitmap);
    end;
  finally
    FreeAndNil(Bitmap);
  end;
end;

我可以单独处理每个案例,但似乎应该有一个函数来执行此操作。我查看了TGPBitmap.Clone函数类,但我只能得到它来生成空白(白色)图像,但无法找到它的任何使用示例。

1 个答案:

答案 0 :(得分:1)

最简单的方法 - 在24位上绘制任何位图并使用现有代码。

最慢的方式 - 通过Pixels []属性获取每个像素的颜色

否则你必须单独处理每种位图。请注意,1,4和8位位图包含调色板的索引,因此您需要从位图调色板获取正确的颜色,15和16位位图像素具有结构xRRRRRGGGGGBBBBB和RRRRRGGGGGGBBBBB,因此您需要提取5位和6位颜色部分并计算整体像素亮度。

相关问题