如何计算位图的近距离裁剪矩形? [英] How to calculate close crop rectangle of a bitmap?

查看:159
本文介绍了如何计算位图的近距离裁剪矩形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过给定的背景颜色键来计算位图关闭裁剪矩形。在以下图片中,您可以看到什么是紧密的作物。左侧是源,右侧输出的缩略图:

I need to calculate a close crop rectangle for a bitmap by a given background color key. In the following pictures you can see what is meant to be the close crop. On the left side is the source, on the right side output of the close crop:

如您所见,我需要找到颜色与背景颜色不同的最上面,最左,最下和最右边的像素关闭裁剪矩形。那么,如何找到那些不同的外部像素来获得关闭裁剪矩形?或者换句话说,如何计算位图的近距离裁剪矩形?

As you can see, I need to find the topmost, leftmost, lowermost and rightmost pixels which differ in color from the background to build the close crop rectangle. So, how to find those differing outer pixels to get the close crop rectangle ? Or, in other words, how to calculate close crop rectangle of a bitmap ?

推荐答案

您可以使用此代码这篇文章的 注释版本

You can use this code (you may follow the commented version of this post as well):

procedure CalcCloseCrop(ABitmap: TBitmap; const ABackColor: TColor;
  out ACropRect: TRect);
var
  X: Integer;
  Y: Integer;
  Color: TColor;
  Pixel: PRGBTriple;
  RowClean: Boolean;
  LastClean: Boolean;
begin
  if ABitmap.PixelFormat <> pf24bit then
    raise Exception.Create('Incorrect bit depth, bitmap must be 24-bit!');

  LastClean := False;
  ACropRect := Rect(ABitmap.Width, ABitmap.Height, 0, 0);

  for Y := 0 to ABitmap.Height-1 do
  begin
    RowClean := True;
    Pixel := ABitmap.ScanLine[Y];
    for X := 0 to ABitmap.Width - 1 do
    begin
      Color := RGB(Pixel.rgbtRed, Pixel.rgbtGreen, Pixel.rgbtBlue);
      if Color <> ABackColor then
      begin
        RowClean := False;
        if X < ACropRect.Left then
          ACropRect.Left := X;
        if X + 1 > ACropRect.Right then
          ACropRect.Right := X + 1;
      end;
      Inc(Pixel);
    end;

    if not RowClean then
    begin
      if not LastClean then
      begin
        LastClean := True;
        ACropRect.Top := Y;
      end;
      if Y + 1 > ACropRect.Bottom then
        ACropRect.Bottom := Y + 1;
    end;
  end;

  if ACropRect.IsEmpty then
  begin
    if ACropRect.Left = ABitmap.Width then
      ACropRect.Left := 0;
    if ACropRect.Top = ABitmap.Height then
      ACropRect.Top := 0;
    if ACropRect.Right = 0 then
      ACropRect.Right := ABitmap.Width;
    if ACropRect.Bottom = 0 then
      ACropRect.Bottom := ABitmap.Height;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  R: TRect;
  Bitmap: TBitmap;
begin
  CalcCloseCrop(Image1.Picture.Bitmap, $00FFA749, R);
  Bitmap := TBitmap.Create;
  try
    Bitmap.SetSize(R.Width, R.Height);
    Bitmap.Canvas.CopyRect(Rect(0, 0, R.Width, R.Height), Image1.Canvas, R);
    Image1.Picture.Bitmap.Assign(Bitmap);
  finally
    Bitmap.Free;
  end;
end;

这篇关于如何计算位图的近距离裁剪矩形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆