我需要一种从python中的String轻松编写压缩TIFF文件的方法.我已经看过Python Imaging Library PIL了,但是我需要编写一个非常特定的TIFF格式,并且PIL目前仅支持未压缩.我需要编写一个LZW压缩的带条纹TIFF,其中仅包含一行简单的文本.我宁愿不必从头开始编写某些东西,但是如果我这样做了.
解决方法:
我过去使用过此代码,因此可以说它有效.该脚本来自1997年,并且PIL尚未实现压缩的TIFF写入.
#
# use "tiffcp" to write compressed TIFF files.
#
# fredrik lundh (may 13, 1997)
#
import os, tempfile
# install standard driver
import Image, TiffImagePlugin
LZW = "lzw"
ZIP = "zip"
JPEG = "jpeg"
PACKBITS = "packbits"
G3 = "g3"
G4 = "g4"
def _save(im, fp, filename):
# check compression mode
try:
compression = im.encoderinfo["compression"]
except KeyError:
# use standard driver
TiffImagePlugin._save(im, fp, filename)
else:
# compress via temporary file
if compression not in (LZW, ZIP, JPEG, PACKBITS, G3, G4):
raise IOError, "unknown compression mode"
file = tempfile.mktemp()
im.save(file, "TIFF")
os.system("tiffcp -c %s %s %s" % (compression, file, filename))
try: os.unlink(file)
except: pass
Image.register_save(TiffImagePlugin.TiffImageFile.format, _save)
if __name__ == "__main__":
# test
im = Image.open("/usr/iv/tip/images/lenna.ppm")
im = im.point(lambda v: v >= 128 and 255, "1")
im.save("lenna.tif", compression=G4)
该代码(附加)仅增加了使用标准PIL库编写压缩TIFF的功能,因此,如果您已将文本写入PIL Image对象,则应该很容易实现.