Working and tested python function to make a landscape image from any resolution by adding background
def makeLandscapeImage(normal_path, output_path, background_path = "bg.png"):
from PIL import Image
try:
# Load images
background_img = Image.open(background_path)
normal_img = Image.open(normal_path)
# Check if normal image has transparency before resizing
has_transparency = normal_img.mode in ("RGBA", "P")
# Use LANCZOS filter for scaling (or another supported PIL filter)
normal_img = normal_img.resize((
int((background_img.height/normal_img.height ) * normal_img.width),
background_img.height
), Image.LANCZOS)
# Preserve transparency if necessary
if has_transparency:
mask = normal_img.convert("L").point(lambda p: 0 if p == 0 else 255) # Create binary transparency mask
normal_img = normal_img.convert("RGBA").copy() # Convert to RGBA with alpha channel
background_img.paste(normal_img, (0, 0), mask) # Use mask for transparency
else:
background_img.paste(normal_img, ((background_img.width - normal_img.width) // 2, 0)) # Center horizontally
# Save the image
background_img.save(output_path)
print(f"Successfully overlaid images and saved to {output_path}")
return output_path
except FileNotFoundError:
print("Error: One or both image files were not found.")
return False
except (ImportError, ValueError) as e:
print(f"Error occurred: {e}")
return False
Comments
Post a Comment