Skip to content

Fix some theoretical problems with png reading #5515

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 20, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/matplotlib/backends/backend_agg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
10 changes: 6 additions & 4 deletions src/_png.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -328,10 +328,12 @@ 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);
} else {
PyErr_SetString(PyExc_IOError, "read past end of file");
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, I see that now. Now, what if bufflen does not end up being the same as length? Are we assuming that an error has been set? Would it make sense for us to set an error if one hasn't been set?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good point. We should probably set an exception in that case. It basically means that it read past the end of the file (which could happen if the file were truncated or something).

}
}
Py_XDECREF(read_method);
Expand Down