rough_work / image_display.py
jkushwaha's picture
Update image_display.py
3163342 verified
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}")