Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-Page tiff resizing python

First post here, although i already spent days of searching for various queries here. Python 3.6, Pillow and tiff processing.
I would like to automate one of our manual tasks, by resizing some of the images from very big to match A4 format. We're operating on tiff format, that sometimes ( often ) contains more than one page. So I wrote:

from PIL import Image,
...
def image_resize(path, dcinput, file):
    dcfake = read_config(configlocation)["resize"]["dcfake"]
    try:
        imagehandler = Image.open(path+file)
        imagehandler = imagehandler.resize((2496, 3495), Image.ANTIALIAS)
        imagehandler.save(dcinput+file, optimize=True, quality=95)
    except Exception:

But the very (not) obvious is that only first page of tiff is being converted. This is not exactly what I expect from this lib, however tried to dig, and found a way to enumerate each page from tiff, and save it as a separate file.

 imagehandler = Image.open(path+file)
        for i, page in enumerate(ImageSequence.Iterator(imagehandler)):
            page = page.resize((2496, 3495), Image.ANTIALIAS)
            page.save(dcinput + "proces%i.tif" %i, optimize=True, quality=95, save_all=True)

Now I could use imagemagick, or some internal commands to convert multiple pages into one, but this is not what I want to do, as it drives to code complication.

My question, is there a unicorn that can help me with either :
1) resizing all pages of given multi-page tiff in the fly
2) build a tiff from few tiffs
I'd like to focus only on python modules.
Thx.

like image 978
Bartek Avatar asked Oct 17 '22 17:10

Bartek


1 Answers

Take a look at this example. It will make every page of a TIF file four times smaller (by halving width and height of every page):

from PIL import Image
from PIL import ImageSequence
from PIL import TiffImagePlugin

INFILE  = 'multipage_tif_example.tif'
OUTFILE = 'multipage_tif_resized.tif'

print ('Resizing TIF pages')
pages = []
imagehandler = Image.open(INFILE)
for page in ImageSequence.Iterator(imagehandler):
    new_size = (page.size[0]/2, page.size[1]/2)
    page = page.resize(new_size, Image.ANTIALIAS)
    pages.append(page)

print ('Writing multipage TIF')
with TiffImagePlugin.AppendingTiffWriter(OUTFILE) as tf:
    for page in pages:
        page.save(tf)
        tf.newFrame()

It's supposed to work since late Pillow 3.4.x versions (works with version 5.1.0 on my machine).

Resources:

  • AppendingTiffWriter discussed here.
  • Sample TIF files can be downloaded here.
like image 103
Andriy Makukha Avatar answered Oct 21 '22 00:10

Andriy Makukha