Certainly! Below is a Python script that accomplishes your request using the PIL (Pillow) library for image processing. The script creates a black background with a specified monitor resolution, resizes the image to fit the background height while maintaining the aspect ratio, and places the resized image in the center of the black background.
First, ensure you have the Pillow library installed. You can install it using pip:
pip install Pillow
Here is the Python code:
from PIL import Image
def create_centered_image(input_image_path, output_image_path, monitor_resolution):
# Load the input image
original_image = Image.open(input_image_path)
# Extract monitor resolution
monitor_width, monitor_height = monitor_resolution
# Create a black background image
background = Image.new('RGB', (monitor_width, monitor_height), (0, 0, 0))
# Resize the original image to fit the background height while maintaining aspect ratio
aspect_ratio = original_image.width / original_image.height
new_height = monitor_height
new_width = int(aspect_ratio * new_height)
if new_width > monitor_width:
new_width = monitor_width
new_height = int(monitor_width / aspect_ratio)
resized_image = original_image.resize((new_width, new_height), Image.ANTIALIAS)
# Calculate position to center the resized image
position = ((monitor_width - new_width) // 2, (monitor_height - new_height) // 2)
# Paste the resized image onto the black background
background.paste(resized_image, position)
# Save the resulting image
background.save(output_image_path)
print(f'Saved centered image to {output_image_path}')
# Set the monitor resolution (width, height)
monitor_resolution = (1920, 1080) # Example resolution
# Define input and output image paths
input_image_path = 'input_image.jpg' # Specify the path to your input image
output_image_path = 'centered_image.jpg' # Output image path
#create the centered image
create_centered_image(input_image_path, output_image_path, monitor_resolution)
Instructions:
- Replace
'input_image.jpg' with the path to your input image.
- Adjust the
monitor_resolution variable to match your desired monitor resolution.
- Run the script, and it will save the centered image as
'centered_image.jpg'.
Explanation:
- The code imports the
Image class from Pillow.
- It defines a function
create_centered_image that takes an input image path, an output path, and the desired monitor resolution.
- It opens the original image, creates a new black background, resizes the original image to fit the height of the background while maintaining its aspect ratio, and computes the position to center the image.
- Finally, it pastes the resized image onto the black background and saves the resulting image to the specified output path.