File size: 2,005 Bytes
3163342
dd7dd45
 
 
 
 
 
 
 
 
 
3163342
dd7dd45
 
 
 
 
3163342
dd7dd45
 
657c50e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dd7dd45
 
 
 
a3280d4
 
657c50e
 
 
 
 
dd7dd45
 
a3280d4
dd7dd45
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
def add_text(image, text, font_size=20, font_color=(255, 0, 0), font_path=None):
    # Create a drawing context
    draw = ImageDraw.Draw(image)

    # Load a font
    if font_path:
        font = ImageFont.truetype(font_path, font_size)
    else:
        font = ImageFont.load_default()

    # Calculate text size and position
    text_width, text_height = draw.textsize(text, font=font)
    width, height = image.size
    text_x = (width - text_width) // 2
    text_y = 10  # Adjust this value for vertical position

    # Draw text on image
    draw.text((text_x, text_y), text, font=font, fill=font_color)

def display_side_by_side_with_captions(image1_path, image2_path, output_path):
    # Open images using Pillow
    image1 = Image.open(image1_path)
    image2 = Image.open(image2_path)

    # Resize images (optional)
    # Here, assuming images are of the same size
    width, height = image1.size
    new_width = width * 2  # Width for the side by side display
    new_height = height

    # Resize both images to match the new dimensions
    image1 = image1.resize((new_width // 2, new_height))
    image2 = image2.resize((new_width // 2, new_height))

    # Create a new image with double width to place both images side by side
    side_by_side = Image.new('RGB', (new_width, new_height))

    # Paste the resized images into the new image
    side_by_side.paste(image1, (0, 0))
    side_by_side.paste(image2, (width, 0))

    # Add captions to each image
    add_caption(image1, "Image 1", font_color=(255, 0, 0))
    add_caption(image2, "Image 2", font_color=(255, 0, 0))

    # Save the side by side image to a file
    side_by_side.save(output_path)

# Example usage:
if __name__ == "__main__":
    image1_path = 'path_to_image1.jpg'
    image2_path = 'path_to_image2.jpg'
    output_path = 'side_by_side_with_captions.jpg'
    display_side_by_side_with_captions(image1_path, image2_path, output_path)

    print(f"Images displayed side by side with captions and saved as {output_path}")