pythonpython-3.xpython-imaging-librarytiff

Unable to convert tiff PIL image to byte array


I have a .tiff image loaded into a PIL Image and I'm trying to obtain its byte array.

This is what I'm doing:

from PIL import Image
import io

def image_to_byte_array(image: Image) -> bytes:
    imgByteArr = io.BytesIO()
    image.save(imgByteArr, format=image.format)
    imgByteArr = imgByteArr.getvalue()
    return imgByteArr

im = Image.open(r"ImagePath")
im_bytes = image_to_byte_array(im)

The problem comes when I'm trying to save the image into imgByteArr.

Some .tiff images are throwing Error setting from dictionary and additionally I also get _TIFFVSetField: : Ignored tag "OldSubfileType" (not supported by libtiff).

Is there any workaround for these cases?

Here is a sample image


Solution

  • I'm in a rush at the moment, but there is something in the image (I'm guessing a tag or compression or some attribute) that prevents you from writing the image.

    You can see the error generated more simply like this:

    from PIL import Image
    
    im = Image.open(...path...)
    im.save('anything.tif')
    

    One way to get rid of all the extended attributes and metadata is to convert the image to a Numpy array and from there back to a PIL Image. This "round-trip" through Numpy can't propagate any attributes, just pixels, so it then works:

    import numpy as np
    from PIL import Image
    
    im = Image.open(...path...)
    
    # Round-trip through Numpy array to strip attributes and metadata
    im = Image.fromarray(np.array(im))
    
    im.save('anything.tif')    # works
    

    I'll investigate further when I have time, but this may work as an interim method.