杰瑞科技汇

ubuntu python pil

Of course! Here is a comprehensive guide on using the Python Imaging Library (PIL), which is now maintained under the package name Pillow, on Ubuntu.

What is PIL/Pillow?

  • PIL (Python Imaging Library): The original library for image processing in Python. It's no longer actively developed.
  • Pillow: A "friendly fork" of PIL. It's the modern, maintained, and recommended successor to PIL. When you install Pillow, you get the PIL module in Python, but it's the Pillow implementation.

In short: You should install and use Pillow.


Step 1: Install Pillow on Ubuntu

The easiest and most reliable way to install Pillow is using pip, Python's package installer.

Update Your System

First, it's always good practice to update your package lists and upgrade existing packages.

sudo apt update
sudo apt upgrade -y

Install Python and Pip

If you don't have Python and pip installed, you can install them with apt. The python3-pip package will also install python3 as a dependency.

sudo apt install python3 python3-pip -y

Install Pillow

Now, use pip to install Pillow. It's good practice to use pip3 to be explicit that you're installing it for Python 3.

pip3 install Pillow

You should see output indicating that Pillow and its dependencies (like Pillow-SIMD for faster image processing) are being downloaded and installed.


Step 2: Verify the Installation

You can quickly verify that Pillow is installed correctly by running a simple Python command in your terminal.

python3 -c "import PIL; print(PIL.__version__)"

If the installation was successful, this command will print the installed version of Pillow (e.g., 0.1).


Step 3: Basic Usage Examples

Here are some common tasks you can perform with Pillow.

Example 1: Opening, Displaying, and Saving an Image

Create a Python script (e.g., basic_image.py):

from PIL import Image
# --- 1. Open an existing image ---
# Make sure you have an image file named 'my_image.jpg' in the same directory
# You can download a sample image or create one.
try:
    img = Image.open('my_image.jpg')
    print(f"Image format: {img.format}")
    print(f"Image size: {img.size}")
    print(f"Image mode: {img.mode}") # e.g., RGB, L, RGBA
except FileNotFoundError:
    print("Error: 'my_image.jpg' not found. Please create a sample image.")
    exit()
# --- 2. Display the image (requires a display server) ---
# This will open the image in your default image viewer.
# It might not work in a headless server environment.
# img.show()
# --- 3. Save the image in a different format ---
# Pillow automatically determines the format from the file extension.
img.save('my_image.png')
print("Image saved as 'my_image.png'")
# --- 4. Create a new blank image ---
# Create a red image (RGB mode) with a size of 200x200 pixels
new_img = Image.new('RGB', (200, 200), color='red')
new_img.save('red_image.png')
print("Created and saved 'red_image.png'")

To run this script:

python3 basic_image.py

Example 2: Resizing and Rotating an Image

Create a script named transform_image.py:

from PIL import Image
# Make sure 'my_image.jpg' exists
try:
    img = Image.open('my_image.jpg')
except FileNotFoundError:
    print("Error: 'my_image.jpg' not found.")
    exit()
# --- 1. Resize the image ---
# Use the .thumbnail() method to resize, maintaining aspect ratio.
# The size is a tuple (width, height).
max_size = (300, 300)
img.thumbnail(max_size)
# Save the resized image
img.save('resized_image.jpg')
print(f"Image resized and saved as 'resized_image.jpg' (New size: {img.size})")
# --- 2. Rotate the image ---
# Open the original image again for the next operation
img_rotated = Image.open('my_image.jpg')
# Rotate 90 degrees counter-clockwise
rotated_img = img_rotated.rotate(90)
# Save the rotated image
rotated_img.save('rotated_image.jpg')
print("Image rotated 90 degrees and saved as 'rotated_image.jpg'")

Example 3: Cropping an Image

Create a script named crop_image.py:

from PIL import Image
try:
    img = Image.open('my_image.jpg')
except FileNotFoundError:
    print("Error: 'my_image.jpg' not found.")
    exit()
# The crop() method takes a 4-tuple: (left, upper, right, lower)
# These are coordinates in pixels.
# Let's crop the center 100x100 pixels.
width, height = img.size
left = (width - 100) / 2
top = (height - 100) / 2
right = (width + 100) / 2
bottom = (height + 100) / 2
# Ensure coordinates are integers
crop_box = (int(left), int(top), int(right), int(bottom))
cropped_img = img.crop(crop_box)
cropped_img.save('cropped_image.jpg')
print(f"Image cropped to 100x100 and saved as 'cropped_image.jpg' (New size: {cropped_img.size})")

Step 4: Common Errors and Troubleshooting

Error: ModuleNotFoundError: No module named 'PIL'

This means Pillow is not installed or not installed for the correct Python version.

  • Solution: Re-run the installation command: pip3 install Pillow.

Error: ImportError: cannot import name 'Image' from 'PIL'

This is less common but can happen if there's a conflict with another package or a very old installation.

  • Solution: Try uninstalling and reinstalling Pillow:
    pip3 uninstall Pillow -y
    pip3 install Pillow --no-cache-dir

Error: OSError: cannot open resource or FileNotFoundError

This means Pillow can't find the image file you're trying to open.

  • Solution: Double-check that the image file is in the same directory as your Python script, or provide the full path to the image file (e.g., Image.open('/home/user/Pictures/my_image.jpg')).

Error: tkinter.TclError: couldn't connect to display :40

This error occurs when you try to use img.show() on a server that doesn't have a graphical display (a "headless" server).

  • Solution: The img.show() method is for quick previews. In production or on a server, you should always save the image to a file instead of trying to display it. If you need to generate images on a headless server, it's fine to use Pillow for all operations except .show().

Useful Resources

分享:
扫描分享到社交APP
上一篇
下一篇