Reputation: 133
How can I combine multiple images into one?
I have an array with a path to the images. These images want to be connected from the right. My images is .png
format.
Thank you
My test code not working:
procedure TCreatorProject.MergeImageList(Images: TImagesList);
var
Img,ImageOut: TGraphic;
ImageTemp: TBitmap;
I: Integer;
FileOutput: String;
begin
FileOutput := ExtractFilePath(Application.ExeName)+'temp\tempimage.png';
for I := Low(Images) to High(Images) do
if not FileExists(Images[I]) then
raise Exception.Create('Chyba: obrázek nebyl nalezen !');
ImageTemp := TBitmap.Create;
try
for I := Low(Images) to High(Images) do
begin
Img.LoadFromFile(Images[I]);
ImageTemp.Width := Img.Width;
ImageTemp.Height := Img.Height;
if I = 0 then
ImageTemp.Canvas.Draw(0, 0, Img)
else
ImageTemp.Canvas.Draw(ImageTemp.Width, ImageTemp.Height, Img);
end;
ImageOut := TPNGObject.Create;
ImageOut.Assign(ImageTemp);
ImageOut.SaveToFile(FileOutput);
finally
ImageTemp.Free;
Img.Free;
ImageOut.Free;
end;
end;
Upvotes: 2
Views: 1034
Reputation: 11860
You are always drawing in the same place and you don't enlarge the output image. Try this instead(Written and tested with DelphiXE7):
program SO32558735;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils, System.IOUtils, System.Types, Vcl.Imaging.pngimage, Vcl.Graphics;
type
TPngImages = array of TPngImage;
function LoadImages(Path : String) : TPngImages;
var
Index : Integer;
Files : TStringDynArray;
begin
Files := TDirectory.GetFiles(Path, '*.png');
SetLength(Result, Length(Files));
for Index := Low(Files) to High(Files) do
begin
Result[Index] := TPngImage.Create;
Result[Index].LoadFromFile(Files[Index]);
end;
end;
function MergeImages(Images: TPngImages) : TPngImage;
var
Image : TPngImage;
Bmp : TBitmap;
X : Integer;
begin
Result := TPngImage.Create;
Bmp := TBitmap.Create;
X := 0;
try
for Image in Images do
begin
// enlarge output image
Bmp.Width := Bmp.Width+Image.Width;
// adjust height if images are not equal
if Image.Height > Bmp.Height then
Bmp.Height := Image.Height;
Bmp.Canvas.Draw(X, 0, Image);
X := Bmp.Width+1;
end;
Result.Assign(Bmp);
finally
Bmp.Free;
end;
end;
var
Images : TPngImages;
Image : TPngImage;
begin
try
try
Images := LoadImages('<input path>');
if Length(Images) < 1 then
raise Exception.Create('No files found!');
Image := MergeImages(Images);
Image.SaveToFile('<output file>');
Image.Free;
finally
for Image in Images do
Image.Free;
end;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;
end.
Upvotes: 3