使用delphi进行作物比例和中心图像

时间:2011-11-26 22:39:27

标签: image delphi scale crop

有没有人知道使用Delphi裁剪,缩放和居中图像(jpg或位图)的方法? 我有一个大分辨率的图像。我希望能够将其缩放到更低的分辨率。目标分辨率的比率可以与原始图像不同。我想保持原始的照片宽高比,因此,我不想延伸到新的分辨率,而是裁剪和居中,以适应原始图像中最佳和松散的最小数据。有谁知道如何使用Delphi完成它?

2 个答案:

答案 0 :(得分:4)

我猜你要调整大小来边缘填充目标图像,然后裁剪超出边界的部分。

这是伪代码。实施将根据您的工作情况而有所不同。

// Calculate aspect ratios
sourceAspectRatio := souceImage.Width / sourceImage.Height;
targetAspectRatio := targetImage.Width / targetImage.Height;

if (sourceAspectRatio > targetAspectRatio) then
begin
  // Target image is narrower, so crop left and right
  // Resize source image
  sourceImage.Height := targetImage.Height;
  // Crop source image
  ..
end
else
begin
  // Target image is wider, so crop top and bottom
  // Resize source image
  sourceImage.Width := targetImage.Width;
  // Crop source image
  ..
end;

答案 1 :(得分:2)

这里只回答你问题的数学部分。请另外询问有关保持最高图像质量的问题。

您需要确定绘制图像的比例以及位置。我建议你试试这个例程:

function CropRect(const Dest: TRect; SrcWidth, SrcHeight: Integer): TRect;
var
  W: Integer;
  H: Integer;
  Scale: Single;
  Offset: TPoint;
begin
  W := Dest.Right - Dest.Left;
  H := Dest.Bottom - Dest.Top;
  Scale := Max(W / SrcWidth, H / SrcHeight);
  Offset.X := (W - Round(SrcWidth * Scale)) div 2;
  Offset.Y := (H - Round(SrcHeight * Scale)) div 2;
  with Dest do
    Result := Rect(Left + Offset.X, Top + Offset.Y, Right - Offset.X,
      Bottom - Offset.Y);
end;

示例调用代码:

type
  TForm1 = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure FormPaint(Sender: TObject);
    procedure FormResize(Sender: TObject);
  private
    FGraphic: TGraphic;
  end;

implementation

{$R *.dfm}

uses
  Jpeg, Math, MyUtils;

procedure TForm1.FormCreate(Sender: TObject);
begin
  FGraphic := TJPEGImage.Create;
  FGraphic.LoadFromFile('MonaLisa.jpg');
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  FGraphic.Free;
end;

procedure TForm1.FormPaint(Sender: TObject);
var
  R: TRect;
begin
  R := CropRect(ClientRect, FGraphic.Width, FGraphic.Height);
  Canvas.StretchDraw(R, FGraphic);
end;

procedure TForm1.FormResize(Sender: TObject);
begin
  Invalidate;
end;
相关问题