TWICImage 的大多功能都非常容易使用, 它最強大的功能是 ImagingFactory: IWICImagingFactory 屬性, 這是個類工廠的接口.
所謂類工廠是 COM 裡的概念, COM 通過類工廠可以自己實例化一些類, 實例化後我們只管使用就是.
通過 TWICImage.ImagingFactory 獲取類工廠後, 再調用 CreateBitmapFlipRotator 建立旋轉變換接口(IWICBitmapFlipRotator).
然後用 IWICBitmapFlipRotator.Initialize 執行變換, 再把變換後的數據賦給 TWICImage, 至此完成變換.
//可以使用的變換方式有:
WICBitmapTransformRotate0 = 0;
WICBitmapTransformRotate90 = $1;
WICBitmapTransformRotate180 = $2;
WICBitmapTransformRotate270 = $3;
WICBitmapTransformFlipHorizontal = $8;
WICBitmapTransformFlipVertical = $10;
測試代碼:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses Wincodec;
procedure TForm1.Button1Click(Sender: TObject);
var
WicImg: TWICImage;
Factory: IWICImagingFactory; {類工廠接口}
FlipRotator: IWICBitmapFlipRotator; {旋轉變換接口}
begin
{先建立 TWICImage 類並載入圖片}
WicImg := TWICImage.Create;
WicImg.LoadFromFile('c:\temp\test.jpg');
{獲取類工廠接口}
Factory := WicImg.ImagingFactory;
{讓類工廠建立旋轉變換接口}
Factory.CreateBitmapFlipRotator(FlipRotator);
{執行旋轉變換, 這裡是旋轉 90度角; 注意旋轉後的數據在 FlipRotator}
FlipRotator.Initialize(WicImg.Handle, WICBitmapTransformRotate90);
{更新 TWICImage 中的圖像}
WicImg.Handle := IWicBitmap(FlipRotator);
{看看}
Canvas.Draw(0, 0, WicImg);
{釋放}
FlipRotator := nil;
Factory := nil;
WicImg.Free;
end;
//還是上面的程序, 給了些返回值的判斷
procedure TForm1.Button2Click(Sender: TObject);
var
WicImg: TWICImage;
Factory: IWICImagingFactory;
FlipRotator: IWICBitmapFlipRotator;
hr: HRESULT;
begin
WicImg := TWICImage.Create;
WicImg.LoadFromFile('c:\temp\test.jpg');
Factory := WicImg.ImagingFactory;
hr := E_INVALIDARG; {先給個無效的返回值}
hr := Factory.CreateBitmapFlipRotator(FlipRotator);
if Succeeded(hr) then {如果上一個函數的返回值成功}
hr := FlipRotator.Initialize(WicImg.Handle, WICBitmapTransformFlipVertical);
if Succeeded(hr) then
WicImg.Handle := IWicBitmap(FlipRotator);
Canvas.Draw(0, 0, WicImg);
FlipRotator := nil;
Factory := nil;
WicImg.Free;
end;
end.