issue #2959: support io.BytesIO objects

This commit is contained in:
Dvořák Václav 2018-01-25 00:44:59 +01:00
parent bc01bb6aae
commit 84f87471f5
2 changed files with 23 additions and 2 deletions

View File

@ -1,5 +1,6 @@
from helper import unittest, PillowTestCase, hopper
from PIL import Image, pdfParser
import io
import os
import os.path
import tempfile
@ -162,6 +163,17 @@ class TestFilePdf(PillowTestCase):
self.assertEqual(pdfParser.decode_text(pdf.info[b"Title"]), "abc")
self.assertEqual(pdfParser.decode_text(pdf.info[b"Producer"]), "pdfParser")
def test_pdf_append_to_bytesio(self):
im = hopper("RGB")
f = io.BytesIO()
im.save(f, format="PDF")
initial_size = len(f.getvalue())
self.assertGreater(initial_size, 0)
im = hopper("P")
f = io.BytesIO(f.getvalue())
im.save(f, format="PDF", append=True)
self.assertGreater(len(f.getvalue()), initial_size)
def test_pdf_parser(self):
pdfParser.selftest()

View File

@ -399,11 +399,20 @@ class PdfParser:
# XXX TODO delete Pages tree recursively
def read_pdf_info_from_file(self, f):
self.buf = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
if hasattr(f, "getbuffer"):
self.buf = f.getbuffer()
need_close = False
elif hasattr(f, "getvalue"):
self.buf = f.getvalue()
need_close = False
else:
self.buf = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
need_close = True
try:
self.read_pdf_info()
finally:
self.buf.close()
if need_close:
self.buf.close()
self.buf = None
def read_pdf_info(self):