📜  pil - Python (1)

📅  最后修改于: 2023-12-03 15:03:46.204000             🧑  作者: Mango

PIL - Python Imaging Library

Python Imaging Library (PIL) is a library for adding support for opening, manipulating, and saving many different image file formats in Python.

Installation

You can use pip to install PIL:

pip install pillow
Usage

To use PIL in your Python project, you need to import it:

from PIL import Image
Opening images

To open an image file, use the Image.open() method:

img = Image.open('path/to/image/file')

You can also open images from a URL:

from urllib import request

url = 'http://example.com/image.jpg'
img = Image.open(request.urlopen(url))
Saving images

To save an image file, use the Image.save() method:

img.save('path/to/image/file')

You can also specify the format to use when saving the image:

img.save('path/to/image/file', 'JPEG')  # save as JPEG image
Manipulating images

PIL provides many methods for manipulating images. Here are some examples:

# Resize image
new_size = (width, height)
img = img.resize(new_size)

# Rotate image
angle = 90
img = img.rotate(angle)

# Crop image
left, top, right, bottom = (x1, y1, x2, y2)
img = img.crop((left, top, right, bottom))

# Convert image to grayscale
img = img.convert('L')
Working with pixels

You can access and modify the pixels of an image using the Image.getpixel() and Image.putpixel() methods:

# Get pixel color
color = img.getpixel((x, y))

# Set pixel color
img.putpixel((x, y), color)
Working with image metadata

PIL allows you to read and write image metadata, such as EXIF data:

# Read EXIF data
from PIL.ExifTags import TAGS

exif = img._getexif()
for tag_id, value in exif.items():
    tag = TAGS.get(tag_id, tag_id)
    print(f"{tag}: {value}")

# Write EXIF data
from PIL import ExifTags

exif = {
    ExifTags.TAGS['Artist']: 'John Doe',
    ExifTags.TAGS['Make']: 'Nikon',
    ExifTags.TAGS['Model']: 'D3100',
}
img.save('path/to/image/file', exif=exif)

For more information, check out the PIL documentation.