How to merge images

How to merge images

         If you would like to merge images into one, you need to calculate the total size of the resulting image by summing the total width or height of the images depending on the merge direction. In the case of the horizontal direction, we will sum images widths and use a direction value equal to `0` in our example, and sum heights for the vertical direction with the value of `1`. Next, create a new merge image with the calculated dimensions and desired background color and place the images to it using draw_image method.

from aspose.imaging import Image, Graphics, Color, Rectangle
from aspose.imaging.fileformats.png import PngColorType
from aspose.imaging.imageoptions import PngOptions
from aspose.imaging.sources import StreamSource
import os
import tempfile
if 'TEMPLATE_DIR' in os.environ:
templates_folder = os.environ['TEMPLATE_DIR']
else:
templates_folder = r"C:\Users\USER\Downloads\templates"
delete_output = 'SAVE_OUTPUT' not in os.environ
data_dir = templates_folder
images = []
files = ["template.png", "template.jpg"]
merge_direction = [0, 1]
max_width = 0
max_height = 0
total_width = 0
total_height = 0
for file_name in files:
image = Image.load(os.path.join(data_dir, file_name))
total_width += image.width
if image.width > max_width:
max_width = image.width
total_height += image.height
if image.height > max_height:
max_height = image.height
images.append(image)
def get_temp_file_name():
f = tempfile.NamedTemporaryFile()
file_name = f.name
f.close()
return file_name
def merge_images(direction):
target_width = 0
target_height = 0
if direction == 0:
target_width = total_width
target_height = max_height
else:
target_width = max_width
target_height = total_height
output_path = data_dir
output_path = os.path.join(output_path, "result" + str(direction) + ".png")
png_options = PngOptions()
png_options.color_type = PngColorType.TRUECOLOR_WITH_ALPHA
tmp_file = get_temp_file_name()
with open(tmp_file, "wb") as stream:
png_options.source = StreamSource(stream)
with Image.create(png_options, target_width, target_height) as image:
image.background_color = Color.white
graphics = Graphics(image)
x = 0
y = 0
graphics.begin_update()
for frame in images:
print("x", x, "y", y)
graphics.draw_image(frame, Rectangle(x, y, frame.width, frame.height))
if direction == 0:
x += frame.width
if direction == 1:
y += frame.height
graphics.end_update()
image.save(output_path)
os.remove(tmp_file)
if delete_output:
os.remove(output_path)
# run
merge_images(0)
merge_images(1)
for image in images:
# to dispose the image we call __exit__()
with image as _:
pass