首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

DelphiX 實戰:TDIB.DoResample 影像重採樣縮放

     編輯:Delphi

TDIB.DoResample 以指定濾鏡模式將影像重採樣至新尺寸,支援縮放、拉伸、非等比縮放。本文提供縮小、橫向壓縮、放大三種模式對比範例。

效果預覽

DoResample 效果

核心程式碼

unit Unit1;
interface
uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, DIB, StdCtrls;
type
  TForm1 = class(TForm)
    DXPaintBox1: TDXPaintBox;
    Button1: TButton; // 載入圖片
    Button2: TButton; // 等比縮小 1/2
    Button3: TButton; // 橫向壓縮 1/2
    Button4: TButton; // 等比放大 1.4x
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
    procedure Button4Click(Sender: TObject);
  end;
var Form1: TForm1;
implementation {$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
const ImgPath1 = 'C:\Temp\DX.jpg';
begin
  DXPaintBox1.DIB.LoadFromFile(ImgPath1);
  DXPaintBox1.Width := DXPaintBox1.DIB.Width;
  DXPaintBox1.Height := DXPaintBox1.DIB.Height;
  DXPaintBox1.Repaint;
end;

procedure TForm1.Button2Click(Sender: TObject); // 等比縮小
var w, h: Integer;
begin
  w := DXPaintBox1.Width div 2; h := DXPaintBox1.Height div 2;
  DXPaintBox1.DIB.DoResample(w, h, TFilterTypeResample(0));
  DXPaintBox1.Repaint;
end;

procedure TForm1.Button3Click(Sender: TObject); // 非等比:寬 1/2、高不變
var w, h: Integer;
begin
  w := DXPaintBox1.Width div 2; h := DXPaintBox1.Height;
  DXPaintBox1.DIB.DoResample(w, h, TFilterTypeResample(0));
  DXPaintBox1.Repaint;
end;

procedure TForm1.Button4Click(Sender: TObject); // 等比放大
var w, h: Integer;
begin
  w := Trunc(DXPaintBox1.Width * 1.4); h := Trunc(DXPaintBox1.Height * 1.4);
  DXPaintBox1.DIB.DoResample(w, h, TFilterTypeResample(0));
  DXPaintBox1.Repaint;
end;
end.

參數說明

DoResample(NewWidth, NewHeight: Integer; FilterType: TFilterTypeResample)
  • NewWidth, NewHeight:目標尺寸,可獨立指定(非等比)
  • FilterType:重採樣濾鏡,TFilterTypeResample(0) 為預設(通常雙線性)
  • 就地修改 DIB 尺寸與像素資料

濾鏡類型對照

三種模式視覺差異

  • 等比縮小 1/2:保持比例,細節合併,適合生成縮圖
  • 橫向壓縮 1/2:畫面變瘦,圓變橢圓,文字變窄
  • 等比放大 1.4x:插值產生新像素,雙線性較柔和,雙三次銳利

應用場景

  • **縮圖生成**:上傳圖片自動產生多種尺寸
  • **UI 適配**:同一素材適配不同解析度螢幕
  • **遊戲 LOD**:遠距離物體使用低解析度版本
  • **列印輸出**:依 DPI 計算目標像素尺寸重採樣
  • **非等比修正**:修正攝影機畸變、投影矯正

進階:保持畫面內容不裁剪的智慧縮放


procedure SmartResample(DIB: TDIB; TargetW, TargetH: Integer; KeepAspect: Boolean);
var srcAR, dstAR: Double; nw, nh: Integer;
begin
  srcAR := DIB.Width / DIB.Height; dstAR := TargetW / TargetH;
  if KeepAspect then begin
    if srcAR > dstAR then begin nw := TargetW; nh := Round(TargetW / srcAR); end
    else begin nw := Round(TargetH * srcAR); nh := TargetH; end;
  end else begin nw := TargetW; nh := TargetH; end;
  DIB.DoResample(nw, nh, rfBicubic);
end;
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
值常數品質速度適用
0rfBox / rfBilinear中快即時縮放、縮圖
1rfBicubic高中高品質放大
2rfLanczos最高慢專業級、離線處理
3rfMitchell高中銳化傾向放大