Write TIFF file in python from String
I need a way to easily write a compressed TIFF file from a String in python. I already look at the Python Imaging Library PIL But I need to write a very specific TIFF format and PIL only supports uncompressed at the moment. I开发者_如何学编程 need to write a LZW compressed, striped TIFF with just one simple line of text in it. I would rather not have to write something from scratch, but if I do I do.
I have just used WinPython to write a TIFF file with LZW compression:
from PIL import Image, TiffImagePlugin
[...]
TiffImagePlugin.WRITE_LIBTIFF = True
im.save(filename, compression = "tiff_lzw")
TiffImagePlugin.WRITE_LIBTIFF = False
(See this WinPython ticket).
(Edit 2014-05-13: Fixed my READ_LIBTIFF/WRITE_LIBTIFF confusion).
(Edit 2015-02-23: Updated the WinPython link).
I've used this code in the past, so I can say that it works. This script is from 1997, and PIL has yet to implement compressed TIFF writing.
#
# 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)
This code (afaict) just adds the ability to write compressed TIFFs using the standard PIL library, so if you've written your text to a PIL Image
object, it should be really easy to implement.
精彩评论