Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read an image inside a zip file with PIL/Pillow

Can I open an image inside a zip with PIL/Pillow without extracting it to disk first?

like image 486
Tor Klingberg Avatar asked Oct 16 '15 08:10

Tor Klingberg


2 Answers

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()))
like image 185
jfs Avatar answered Oct 19 '22 11:10

jfs


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)
like image 37
Tor Klingberg Avatar answered Oct 19 '22 11:10

Tor Klingberg