From 87ca28745340b25f05b91945f93888d08ba69d23 Mon Sep 17 00:00:00 2001 From: Oscar Gustafsson Date: Wed, 17 Apr 2024 07:11:24 +0200 Subject: [PATCH] Backport PR #28032: FIX: ensure images are C order before passing to pillow --- lib/matplotlib/image.py | 1 + lib/matplotlib/tests/test_image.py | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 5b0152505397..2e13293028ca 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -1640,6 +1640,7 @@ def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None, # we modify this below, so make a copy (don't modify caller's dict) pil_kwargs = pil_kwargs.copy() pil_shape = (rgba.shape[1], rgba.shape[0]) + rgba = np.require(rgba, requirements='C') image = PIL.Image.frombuffer( "RGBA", pil_shape, rgba, "raw", "RGBA", 0, 1) if format == "png": diff --git a/lib/matplotlib/tests/test_image.py b/lib/matplotlib/tests/test_image.py index fdbba7299d2b..1602f86716cb 100644 --- a/lib/matplotlib/tests/test_image.py +++ b/lib/matplotlib/tests/test_image.py @@ -205,6 +205,14 @@ def test_imsave(fmt): assert_array_equal(arr_dpi1, arr_dpi100) +@pytest.mark.parametrize("origin", ["upper", "lower"]) +def test_imsave_rgba_origin(origin): + # test that imsave always passes c-contiguous arrays down to pillow + buf = io.BytesIO() + result = np.zeros((10, 10, 4), dtype='uint8') + mimage.imsave(buf, arr=result, format="png", origin=origin) + + @pytest.mark.parametrize("fmt", ["png", "pdf", "ps", "eps", "svg"]) def test_imsave_fspath(fmt): plt.imsave(Path(os.devnull), np.array([[0, 1]]), format=fmt)