Can I open an image inside a zip with PIL/Pillow without extracting it to disk first?
The recent Pillow releases do not require .seek()
:
#!/usr/bin/env python
import sys
from zipfile import ZipFile
from PIL import Image # $ pip install pillow
filename = sys.argv[1]
with ZipFile(filename) as archive:
for entry in archive.infolist():
with archive.open(entry) as file:
img = Image.open(file)
print(img.size, img.mode, len(img.getdata()))
Pythons zipfile does provide a ZipFile.open()
that returns a file object for a file inside the zip, and Pillow's Image.open()
can take file object to open from. Unfortunately the zipfile object does not provide the seek()
method that Image.open()
needs.
Instead read the image file into a string in RAM (if it is not too big), and use StringIO to get a file object for Image.open()
:
from zipfile import ZipFile
from PIL import Image
from StringIO import StringIO
archive = ZipFile("file.zip", 'r')
image_data = archive.read("image.png")
fh = StringIO(image_data)
img = Image.open(fh)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With