有人知道在Delphi中裁剪、缩放和居中图像(jpg或位图)的方法吗?
我有一张高分辨率的图片,想将其缩放到低分辨率。目标分辨率的比率可能与原始图片不同。我想保持原始照片的纵横比,因此不想拉伸到新的分辨率,而是裁剪并居中,以最好地适应并尽量少地丢失原始图片的数据。有人知道如何使用Delphi实现吗?
// 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;
这里只回答您的数学问题。请另外提出一个关于保持最大图像质量的问题。
您需要确定绘制图像的比例和位置。我建议您尝试以下程序:
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;
Max()
改为Min()
。 - NGLN