feelfree
feelfree

Reputation: 11753

how to set the TIFF image resolution with Python PIL

I use the following scripts to set the resolution of a tiff image:

from PIL import Image
im=Image.open('abc.bmp')
im.info
im=im.convert('1')
im.info
im.save('abc.tif')

As I can clearly see that the resolution of the image is ('dpi': (300, 300)), I assume that the output TIFF image should have the resolution 300 DPI. However, the output resolution is undefined when I read the head file information of the TIFF File. Any ideas on setting the resolution? Thanks.

Upvotes: 3

Views: 6031

Answers (1)

msw
msw

Reputation: 43487

I've use ImageMagick's identify program to read the file meta-data. My source file was the venerable Lena image for which:

$ identify -verbose lena.jpg
…
Resolution: 72x72
…

where the resolution is contained in the JFIF block. PIL† does not appear to translate this JFIF block in Image.open:

>>> im = Image.open('lena.jpg')
>>> im.info 
{'exif': b'Exif\x00\x00II*\x00\x08…',
 'jfif': 257,
 'jfif_density': (1, 1),
 'jfif_unit': 0,
 'jfif_version': (1, 1)}

However, you can specify resolution for TIFF output

>>> im.save('lena.tiff', dpi=(300, 300))
>>> lena = Image.open('lena.tiff')
>>> lena.info
{'compression': 'raw', 'dpi': (300.0, 300.0)}

and identify agrees

$ identify -verbose lena.tiff
…
  Resolution: 300x300
…

†A note on the apparent death of PIL

As far as I can tell, the last release of PIL was in 2009 which was supplanted by the Pillow Project which appears to be in active development. Unfortunately, Pillow didn't change the package name, so it if you write:

import PIL

or

from PIL import Image

you have know way of knowing which library you are working with except by

>>> PIL.PILLOW_VERSION 

which should yield a NameError under PIL but a version number ('2.9.0' is latest release) under Pillow.

If you are using PIL, not Pillow, I have no idea if the answer above will work for you, and I've hit the limit as to how much PIL-ish code I want to read today.

Upvotes: 5

Related Questions