杰瑞科技汇

Python PIL在Windows下如何高效处理图像?

Of course! Here's a comprehensive guide to using the Python Imaging Library (PIL), specifically its modern fork Pillow, on Windows.

Python PIL在Windows下如何高效处理图像?-图1
(图片来源网络,侵删)

This guide covers:

  1. Installation (The most common hurdle on Windows)
  2. Basic Usage with code examples
  3. Working with File Paths (Crucial for Windows)
  4. Saving Images
  5. Common Issues and Solutions

Installation: The Key is Pillow

The original PIL library is no longer maintained. You should always use its active fork, Pillow. The import name remains PIL, but you install it via pip.

Step 1: Install Python

If you don't have Python, download it from the official Python website: python.org. Important: During installation, make sure to check the box that says "Add Python to PATH". This makes it much easier to run Python from the command line.

Step 2: Install Pillow using pip

Open a command prompt (search for cmd or PowerShell in the Start Menu) and run the following command:

Python PIL在Windows下如何高效处理图像?-图2
(图片来源网络,侵删)
pip install Pillow

If you have multiple Python versions, you might need to be more specific:

py -m pip install Pillow

or

python -m pip install Pillow

This command downloads and installs Pillow and all its necessary dependencies.


Basic Usage: Opening and Displaying an Image

Let's start with a simple script. This script will open an image, display it, and print some information about it.

Python PIL在Windows下如何高效处理图像?-图3
(图片来源网络,侵删)

Create a Sample Image

First, let's create a simple image using Pillow itself so you can run this example without needing to find a picture.

# create_sample_image.py
from PIL import Image
# Create a new RGB image (800x600) with a blue background
img = Image.new('RGB', (800, 600), color='blue')
# Save the image to your current directory
img.save('blue_background.png')
print("Created a sample image named 'blue_background.png'")

Run this script. You will now have a file named blue_background.png in the same folder.

The Main Script: open_and_display.py

Now, let's write the main script to open and display this image.

# open_and_display.py
from PIL import Image
try:
    # --- 1. Open an image file ---
    # The image 'blue_background.png' should be in the same folder as this script.
    image_path = "blue_background.png"
    img = Image.open(image_path)
    # --- 2. Display image information ---
    print(f"Image format: {img.format}")
    print(f"Image mode: {img.mode}") # e.g., RGB, RGBA, L (grayscale)
    print(f"Image size: {img.size}") # A tuple (width, height)
    print(f"Image filename: {img.filename}")
    # --- 3. Display the image ---
    # This will open the image using your default image viewer (e.g., Photos app).
    img.show()
    # --- 4. Basic Manipulation: Resize ---
    # Create a thumbnail (modifies the image in-place)
    img.thumbnail((200, 200))
    print("\nResized image to a thumbnail.")
    img.save("thumbnail.png") # Save the new, smaller image
    img.show() # Show the resized image
except FileNotFoundError:
    print(f"Error: The file '{image_path}' was not found.")
    print("Make sure the image is in the same directory as your script.")
except Exception as e:
    print(f"An error occurred: {e}")

To run this:

  1. Save the code as open_and_display.py in the same folder where you created blue_background.png.
  2. Open a command prompt in that folder (cd path\to\your\folder).
  3. Run the script: python open_and_display.py

You should see your image open in the default Windows Photos app, and information printed to the console.


Working with File Paths on Windows

This is a very common point of confusion. Windows uses backslashes (\) in file paths, but Python uses backslashes as escape characters (e.g., \n for newline).

The Problem:

# WRONG - This will likely cause a FileNotFoundError or other errors
img = Image.open("C:\Users\YourUser\Pictures\my photo.jpg")
# The \U in \Users is interpreted as a Unicode escape sequence!

The Solutions:

Solution 1: Use Raw Strings (Recommended)

Prefix the string with r. This tells Python to treat backslashes literally.

import os
from PIL import Image
# Correct way using a raw string
image_path = r"C:\Users\YourUser\Pictures\my photo.jpg"
img = Image.open(image_path)

Solution 2: Use Forward Slashes

Python is smart enough to handle forward slashes () even on Windows. This is often the simplest solution.

# Also correct and often easier to read
image_path = "C:/Users/YourUser/Pictures/my photo.jpg"
img = Image.open(image_path)

Solution 3: Use os.path (Best for Dynamic Paths)

If you are building paths from variables, use the os.path module to ensure it works correctly on any operating system.

import os
from PIL import Image
folder = "C:/Users/YourUser/Pictures"
filename = "my photo.jpg"
image_path = os.path.join(folder, filename)
# This path will be correct whether you're on Windows, macOS, or Linux
img = Image.open(image_path)

Saving Images

Saving images is just as easy as opening them. You can change the format, quality, and more.

from PIL import Image
# Open an image
img = Image.open("blue_background.png")
# --- Save as a different format ---
# Save as a JPEG (Note: JPEG doesn't support transparency, so convert to RGB first)
if img.mode == 'RGBA':
    img = img.convert('RGB')
img.save("blue_background.jpg", "JPEG")
# --- Save with specific quality (for JPEGs) ---
img.save("blue_background_high_quality.jpg", "JPEG", quality=95)
img.save("blue_background_low_quality.jpg", "JPEG", quality=15)
# --- Save as a PNG with compression ---
img.save("blue_background_compressed.png", "PNG", compress_level=9) # 0-9, 9 is max compression
print("Saved images in different formats and qualities.")

Common Issues and Solutions

Issue 1: ModuleNotFoundError: No module named 'PIL'

This means Pillow is not installed correctly.

  • Solution: Reinstall Pillow carefully.
    1. Open Command Prompt as Administrator.
    2. Run: pip uninstall Pillow
    3. Run: pip install Pillow If you have multiple Python versions, use py -m pip install Pillow.

Issue 2: FileNotFoundError

This means the script can't find the image file.

  • Solution: Double-check your file path. Use os.listdir() to see what files are in the current directory.
    import os
    print("Files in current directory:")
    print(os.listdir('.'))

    Then, make sure your path string is correct (see section 3 on file paths).

Issue 3: OSError: cannot identify image file

This means the file exists, but Pillow cannot read it. It might be corrupted, not an image, or in a format that Pillow doesn't support without additional libraries (like TIFF support).

  • Solution:
    1. Try opening the image file manually by double-clicking it. Does it open?
    2. Ensure the file extension matches the actual content (e.g., a .jpg file is actually a JPEG).
    3. For specialized formats like .tiff or .webp, you might need to install additional libraries:
      pip install pillow-heif  # For HEIF/HEIC images
      pip install webp  # For WebP images (sometimes included in Pillow)

Issue 4: img.show() doesn't work or is slow

The img.show() command saves the image to a temporary file and calls an external viewer. On Windows, this usually works, but it can be slow or fail in certain environments (like some cloud IDEs or servers).

  • Solution: For more control, especially for saving images instead of displaying them, use libraries like matplotlib.

    import matplotlib.pyplot as plt
    from PIL import Image
    img = Image.open("blue_background.png")
    # Display the image using matplotlib
    plt.imshow(img)
    plt.axis('off') # Hide axes
    plt.title("My Image")
    plt.show()
分享:
扫描分享到社交APP
上一篇
下一篇