Ma Su: “Zhuge, I am currently working on an e-commerce website and need to process a large number of product images. Some need to be cropped, and others need watermarks. Processing them one by one is exhausting. Is there a good way to do it?”
Zhuge Liang: “Haha, this is simple. Python is your reliable assistant! Let me teach you how to use Python’s PIL library to batch process images.”
Ma Su: “PIL? What kind of magical thing is that?”
Zhuge Liang: “PIL stands for Python Imaging Library, a magical tool specifically for processing images in Python. First, let’s install it:
pip install Pillow
Once installed, we can start processing images.”
Ma Su: “Great! So how do we use it?”
Zhuge Liang: “Let me show you some magic! First, let’s see how to batch crop images:
from PIL import Image
import os
def batch_crop_images(input_folder, output_folder, crop_size):
# Ensure the output folder exists
if not os.path.exists(output_folder):
os.makedirs(output_folder)
# Iterate through all images in the input folder
for filename in os.listdir(input_folder):
if filename.endswith(('.png', '.jpg', '.jpeg')):
# Open the image
with Image.open(os.path.join(input_folder, filename)) as img:
# Get the center point of the image
center_x = img.width // 2
center_y = img.height // 2
# Calculate the crop area
left = center_x - crop_size[0] // 2
top = center_y - crop_size[1] // 2
right = left + crop_size[0]
bottom = top + crop_size[1]
# Crop and save
cropped_img = img.crop((left, top, right, bottom))
cropped_img.save(os.path.join(output_folder, filename))
This code acts like an automatic cropping machine, cropping all images in the folder to the specified size.
Ma Su: “Wow! That’s amazing! What about adding watermarks?”
Zhuge Liang: “Adding watermarks is also very simple. Look at this code:
from PIL import Image, ImageDraw, ImageFont
import os
def add_watermark(input_folder, output_folder, watermark_text):
if not os.path.exists(output_folder):
os.makedirs(output_folder)
for filename in os.listdir(input_folder):
if filename.endswith(('.png', '.jpg', '.jpeg')):
# Open the image
with Image.open(os.path.join(input_folder, filename)) as img:
# Create a drawing object to draw on the image
draw = ImageDraw.Draw(img)
# Set the font and size
font = ImageFont.truetype('arial.ttf', 36)
# Calculate watermark position (bottom right corner)
position = (img.width - 200, img.height - 50)
# Add watermark text
draw.text(position, watermark_text, font=font, fill=(255, 255, 255, 128))
# Save the image
img.save(os.path.join(output_folder, filename))
This magic can add a beautiful semi-transparent watermark to all images!
Ma Su: “Awesome! But what if I want to use both functions together?”
Zhuge Liang: “Then combine them! Look at this ultimate version:
def process_images(input_folder, output_folder, crop_size, watermark_text):
temp_folder = 'temp_cropped'
# First crop
batch_crop_images(input_folder, temp_folder, crop_size)
# Then add watermark
add_watermark(temp_folder, output_folder, watermark_text)
# Clean up temporary folder
for filename in os.listdir(temp_folder):
os.remove(os.path.join(temp_folder, filename))
os.rmdir(temp_folder)
# Example usage
process_images(
'input_images',
'output_images',
(800, 800),
'© e-commerce'
)
Ma Su: “This is incredible! Now I can process all images at once. Is there anything I need to be aware of?”
Zhuge Liang: “Indeed, there are a few points to note:
-
Make sure to create the input folder and place the images to be processed inside it.
-
Ensure the appropriate font file is installed on your system.
-
Be mindful of memory usage when processing a large number of images.
Remember, Python is like a diligent little helper; as long as you master the right methods, it can save you a lot of time!”
Ma Su: “I’ve learned a lot! Now I can easily process the product images.”
Zhuge Liang: “Good! Practical application is the real skill. Once you master this, I’ll teach you more magical tricks of Python!”
Tip: If you want to try this code, remember to prepare:
-
Install Python and the Pillow library.
-
Create input and output folders.
-
Prepare some test images.
Come and try this little image processing assistant!