Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3675841

Browse files
committed
Merge pull request #5910 from mdboom/image-read-from-url
Fix reading/writing from urllib.request objects
2 parents cc1b0c9 + 879c186 commit 3675841

File tree

2 files changed

+34
-10
lines changed

2 files changed

+34
-10
lines changed

lib/matplotlib/tests/test_image.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import io
66
import os
77

8+
from nose.plugins.attrib import attr
9+
810
import numpy as np
911

1012
from matplotlib.testing.decorators import (image_comparison,
@@ -517,6 +519,13 @@ def test_minimized_rasterized():
517519
assert False
518520

519521

522+
@attr('network')
523+
def test_load_from_url():
524+
req = six.moves.urllib.request.urlopen(
525+
"http://matplotlib.org/_static/logo_sidebar_horiz.png")
526+
Z = plt.imread(req)
527+
528+
520529
if __name__=='__main__':
521530
import nose
522531
nose.runmodule(argv=['-s','--with-doctest'], exit=False)

src/_png.cpp

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,17 @@ static PyObject *Py_write_png(PyObject *self, PyObject *args, PyObject *kwds)
206206
goto exit;
207207
}
208208
buff.cursor = 0;
209-
} else if ((fp = mpl_PyFile_Dup(py_file, (char *)"wb", &offset))) {
209+
} else {
210+
#if PY3K
211+
if (close_file) {
212+
#else
213+
if (close_file || PyFile_Check(py_file)) {
214+
#endif
215+
fp = mpl_PyFile_Dup(py_file, (char *)"wb", &offset);
216+
}
217+
}
218+
219+
if (fp) {
210220
close_dup_file = true;
211221
} else {
212222
PyErr_Clear();
@@ -374,10 +384,23 @@ static PyObject *_read_png(PyObject *filein, bool float_result)
374384
py_file = filein;
375385
}
376386

377-
if ((fp = mpl_PyFile_Dup(py_file, (char *)"rb", &offset))) {
387+
#if PY3K
388+
if (close_file) {
389+
#else
390+
if (close_file || PyFile_Check(py_file)) {
391+
#endif
392+
fp = mpl_PyFile_Dup(py_file, (char *)"rb", &offset);
393+
}
394+
395+
if (fp) {
378396
close_dup_file = true;
397+
if (fread(header, 1, 8, fp) != 8) {
398+
PyErr_SetString(PyExc_IOError, "error reading PNG header");
399+
goto exit;
400+
}
379401
} else {
380402
PyErr_Clear();
403+
381404
PyObject *read_method = PyObject_GetAttrString(py_file, "read");
382405
if (!(read_method && PyCallable_Check(read_method))) {
383406
Py_XDECREF(read_method);
@@ -387,14 +410,6 @@ static PyObject *_read_png(PyObject *filein, bool float_result)
387410
goto exit;
388411
}
389412
Py_XDECREF(read_method);
390-
}
391-
392-
if (fp) {
393-
if (fread(header, 1, 8, fp) != 8) {
394-
PyErr_SetString(PyExc_IOError, "error reading PNG header");
395-
goto exit;
396-
}
397-
} else {
398413
_read_png_data(py_file, header, 8);
399414
}
400415

0 commit comments

Comments
 (0)