我正在尝试更改我的 PNG 图像的 dpi 并像这样使用 Pillow/PIL 将它们转换为 TIFF,
from PIL import Image
import os
for fl in os.listdir(os.getcwd()):
name, ext = fl.split(".")
im = Image.open(fl)
im.save(name + ".tiff", dpi=(500,500), compression="tiff_jpeg")
print("Done '{}'".format(name))
如果未设置 compression kwarg,它工作正常,但我最终从我的 1MB PNG 文件中得到了巨大的 100MB TIFF 文件。如果我将压缩类型设置为任何可用的 options ,我最终遇到以下错误:
Traceback (most recent call last):
File "<ipython-input-1-3631f05e05f4>", line 7, in <module>
im.save(name + ".tiff", dpi=(500,500), compression="tiff_jpeg")
File "C:\Users\Patrick\Anaconda3\lib\site-packages\PIL\Image.py", line 1687, in save
save_handler(self, fp, filename)
File "C:\Users\Patrick\Anaconda3\lib\site-packages\PIL\TiffImagePlugin.py", line 1457, in _save
raise IOError("encoder error %d when writing image file" % s)
OSError: encoder error -2 when writing image file
在 Image.save 的文档中它提到的方法只有在我安装了 libtiff 库时才可以进行压缩。
这是我正在使用的 Python 和 Pillow 的版本:
Python 3.5.1 |Anaconda 4.0.0 (64-bit)| (default, Feb 16 2016, 09:49:46) [MSC v.1900 64 bit (AMD64)] on win32
libtiff: 4.0.6-vc14_2 [vc14]
pillow: 3.2.0-py35_1
此错误的可能原因是什么?我可以采取哪些步骤来解决?这是我第一次使用 Pillow/PIL,我不确定从哪里开始。
请您参考如下方法:
我自己也被这个问题困扰了,所以我想我会分享我的发现,尽管这个问题已经存在几个月了。
tiff_jpeg 压缩指的是“旧式”JPEG 编码的 TIFF 文件,现已过时。使用 compression='jpeg' 而不是 compression='tiff_jpeg' 对我有用。
compression 的可用选项当前可以在 https://github.com/python-pillow/Pillow/blob/master/PIL/TiffImagePlugin.py 的 COMPRESSION_INFO 字典中找到. tiff_lzw 压缩也没有在文档中提及,但可以为我在 Windows 上使用 Pillow 3.4 创建一个 LZW 编码的 TIFF。
