From 84f87471f5e5ad972b2c304bd4505b54cbf3a5e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dvo=C5=99=C3=A1k=20V=C3=A1clav?= Date: Thu, 25 Jan 2018 00:44:59 +0100 Subject: [PATCH] issue #2959: support io.BytesIO objects --- Tests/test_file_pdf.py | 12 ++++++++++++ src/PIL/pdfParser.py | 13 +++++++++++-- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/Tests/test_file_pdf.py b/Tests/test_file_pdf.py index 8edf875cd..fe460d965 100644 --- a/Tests/test_file_pdf.py +++ b/Tests/test_file_pdf.py @@ -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() diff --git a/src/PIL/pdfParser.py b/src/PIL/pdfParser.py index 3a386f493..c5755dae4 100644 --- a/src/PIL/pdfParser.py +++ b/src/PIL/pdfParser.py @@ -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):