From 17aad94ab367d38235af8890470edc1f85f7bf3c Mon Sep 17 00:00:00 2001 From: Michael Droettboom Date: Wed, 18 Nov 2015 22:10:29 -0500 Subject: [PATCH 1/2] Fix some theoretical problems with png reading --- lib/matplotlib/image.py | 4 ++-- src/_png.cpp | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 188d991981a6..7a3cd1dc9c39 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -1279,8 +1279,8 @@ def pilread(fname): from PIL import Image except ImportError: return None - image = Image.open(fname) - return pil_to_array(image) + with Image.open(fname) as image: + return pil_to_array(image) handlers = {'png': _png.read_png, } if format is None: diff --git a/src/_png.cpp b/src/_png.cpp index 6a2998982718..eee2cf085aa2 100644 --- a/src/_png.cpp +++ b/src/_png.cpp @@ -328,10 +328,10 @@ static void _read_png_data(PyObject *py_file_obj, png_bytep data, png_size_t len Py_ssize_t bufflen; if (read_method) { result = PyObject_CallFunction(read_method, (char *)"i", length); - } - if (PyBytes_AsStringAndSize(result, &buffer, &bufflen) == 0) { - if (bufflen == (Py_ssize_t)length) { - memcpy(data, buffer, length); + if (PyBytes_AsStringAndSize(result, &buffer, &bufflen) == 0) { + if (bufflen == (Py_ssize_t)length) { + memcpy(data, buffer, length); + } } } Py_XDECREF(read_method); From d7d70389427e91496556d085da6de1d2c81ce668 Mon Sep 17 00:00:00 2001 From: Michael Droettboom Date: Fri, 20 Nov 2015 14:26:17 -0500 Subject: [PATCH 2/2] Set exception if read past end of file --- lib/matplotlib/backends/backend_agg.py | 1 + src/_png.cpp | 2 ++ 2 files changed, 3 insertions(+) diff --git a/lib/matplotlib/backends/backend_agg.py b/lib/matplotlib/backends/backend_agg.py index 257e9c7dbae8..5dea52363e86 100644 --- a/lib/matplotlib/backends/backend_agg.py +++ b/lib/matplotlib/backends/backend_agg.py @@ -526,6 +526,7 @@ def print_png(self, filename_or_obj, *args, **kwargs): close = True else: close = False + try: _png.write_png(renderer._renderer, filename_or_obj, self.figure.dpi) finally: diff --git a/src/_png.cpp b/src/_png.cpp index eee2cf085aa2..952d39ef6456 100644 --- a/src/_png.cpp +++ b/src/_png.cpp @@ -331,6 +331,8 @@ static void _read_png_data(PyObject *py_file_obj, png_bytep data, png_size_t len if (PyBytes_AsStringAndSize(result, &buffer, &bufflen) == 0) { if (bufflen == (Py_ssize_t)length) { memcpy(data, buffer, length); + } else { + PyErr_SetString(PyExc_IOError, "read past end of file"); } } }