2007. május 31., csütörtök

Bitmap blending

Problem/Question/Abstract:

How to show an image changing into another.

Answer:

In a previous post I provided a function that takes 2 TBitmap arguments and returns a crossfaded image obtained by combining the two bitmaps.

That can be used to make an animation that shows a bitmap morphing into another bitmap.

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, jpeg;

type
TForm1 = class(TForm)
Button1: TButton;
Image3: TImage;
esteps: TEdit;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

function mix(img1, img2: TBitmap; steps, stepno: integer): TBitmap;
var
x, y, height, width: integer;
pimg1, pimg2, pres: PByteArray;
res: TBitmap;
begin
res := TBitmap.Create;
if img1.Height > img2.Height then
height := img2.Height
else
height := img1.Height;
if img1.Width > img1.Width then
width := img2.Width
else
width := img1.Width;

img1.PixelFormat := pf24bit;
img2.PixelFormat := pf24bit;
res.PixelFormat := pf24bit;
res.Width := width;
res.Height := height;

for y := 0 to height - 1 do
begin
pimg1 := img1.ScanLine[y];
pimg2 := img2.ScanLine[y];
pres := res.ScanLine[y];

for x := 0 to width - 1 do
begin
pres^[x * 3] := pimg1^[x * 3] * (steps - stepno) div steps +
pimg2[x * 3] * stepno div steps;
pres^[x * 3 + 1] := pimg1^[x * 3 + 1] * (steps - stepno) div steps +
pimg2[x * 3 + 1] * stepno div steps;
pres^[x * 3 + 2] := pimg1^[x * 3 + 2] * (steps - stepno) div steps +
pimg2[x * 3 + 2] * stepno div steps;
end;
end;
result := res;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
steps, i: integer;
img1, img2: TBitmap;
begin
if esteps.text <> '' then
begin
steps := strtoint(esteps.text);
img1 := TBitmap.Create;
img2 := TBitmap.Create;
img1.LoadFromFile('e:\untitled.bmp');
img2.LoadFromFile('e:\untitled1.bmp');
for i := 1 to steps do
begin
image3.Picture.Bitmap := mix(img1, img2, steps, i);
image3.Refresh;
sleep(30);
end;
img1.Free;
img2.Free;
end
else
messagedlg('Please provide the number of steps for morphing', mterror, [mbok], 0);
end;

end.

I have a form with a button on it, a TImage object and an edit box. The editbox is used to provide the number of steps in wich morphing will occur. I load two bitmaps and the morphing is showed in the TImage object. The function mix is mixing two images in a certain proportion calculated from the values of the steps and stepno.


Nincsenek megjegyzések:

Megjegyzés küldése