Windows10 x64+Python2.7.14下,如何用Wand库将多JPEG转单压缩TIFF?
Since you already know ImageMagick's command line tool gets the job done perfectly, Wand is just the Python wrapper for ImageMagick—so we can replicate that exact functionality without leaving your Python script. Let's walk through how to do this properly.
Step 1: Ensure Your Environment is Set Up
First, make sure you have the right versions installed:
- Install Wand for Python 2.7: Run
pip install wand==0.6.10(this is the last stable version compatible with Python 2.7) - Double-check that ImageMagick is installed on your Windows machine, and that its path is added to your system's
PATHenvironment variable. Alternatively, you can set theMAGICK_HOMEenvironment variable in your script to point directly to your ImageMagick installation folder (e.g.,C:\Program Files\ImageMagick-7.1.1-Q16-HDRI).
Step 2: Python Code to Merge and Compress
Here's a code snippet that will take your list of JPEG files, merge them into a single TIFF with JPEG compression (matching the 100MB → 7MB compression you saw with ImageMagick):
from wand.image import Image from wand.color import Color # List of your input JPEG paths jpeg_files = ["image1.jpg", "image2.jpg", "image3.jpg"] # Create a new multi-page TIFF with JPEG compression with Image() as tiff: # Set background color to handle any transparency (optional but safe) tiff.background_color = Color('white') # Configure core compression settings tiff.compression = 'jpeg' tiff.compression_quality = 85 # Adjust to balance size/quality (1-100) tiff.depth = 8 # Match standard JPEG bit depth # Add each JPEG as a page in the TIFF for jpeg_path in jpeg_files: with Image(filename=jpeg_path) as img: # Ensure image is in RGB format (JPEG doesn't support alpha) img.format = 'jpeg' tiff.sequence.append(img) # Save the final compressed TIFF tiff.save(filename='compressed_output.tiff')
Key Details to Note
- Compression Control: The
compression='jpeg'flag mirrors the behavior of your workingmagickcommand. Tweakcompression_qualityto adjust file size vs. image clarity—85 is a reliable default, but you can lower it for smaller files or raise it for sharper results. - Multi-Page Handling: Using
tiff.sequence.append()adds each JPEG as a separate page in the TIFF, just like the ImageMagick command line does. - Windows Paths: If your JPEG file paths include spaces, use raw strings (e.g.,
r"C:\My Photos\vacation.jpg") to avoid parsing issues.
Why This Works (And Why Pillow/Libtiff Failed)
Pillow's TIFF compression support can be inconsistent on Windows, often due to incomplete underlying library configurations. Wand, by contrast, directly leverages the ImageMagick engine you already confirmed works—so it will produce the exact same compressed TIFF output as your magick command line tool.
内容的提问来源于stack exchange,提问作者Abdullah Nehir

