Python PIL: Batch Image Processing

To bulk edit image content, you can use Python’s PIL library (Python Imaging Library) to read and modify images.

Below is an example code showing how to use the PIL library to batch modify image content.

from PIL import Image

# 打开图片
image = Image.open('input.jpg')

# 修改图片内容
# 这里是一个简单的示例,将图片的所有像素点颜色反转
inverted_image = Image.eval(image, lambda x: 255 - x)

# 保存修改后的图片
inverted_image.save('output.jpg')

The code above is for manipulating a single image. If you want to change the content of multiple images in bulk, you can use a loop structure to iterate through all the image files and modify and save each image.

For example, if you have multiple image files named image1.jpg, image2.jpg, etc., you can write the following code to batch modify the image content:

from PIL import Image
import glob

# 获取所有图片文件路径
image_files = glob.glob('*.jpg')

# 遍历所有图片文件
for file in image_files:
    # 打开图片
    image = Image.open(file)

    # 修改图片内容
    # 这里是一个简单的示例,将图片的所有像素点颜色反转
    inverted_image = Image.eval(image, lambda x: 255 - x)

    # 保存修改后的图片
    inverted_image.save('modified_' + file)

The above code iterates through all .jpg files in the current directory and makes modifications to each image. The modified images will be saved in the current directory with “modified_” as the file name prefix. You can customize and adjust based on your specific needs.

bannerAds