Skip to content
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

Allow PixelAccess to use Python __int__ when parsing x and y #5206

Merged
merged 2 commits into from Mar 31, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 16 additions & 0 deletions Tests/test_image_access.py
Expand Up @@ -23,6 +23,11 @@
except ImportError:
cffi = None

try:
import numpy
except ImportError:
numpy = None


class AccessTest:
# initial value
Expand Down Expand Up @@ -66,6 +71,10 @@ def test_sanity(self):
pix1 = im1.load()
pix2 = im2.load()

for x, y in ((0, "0"), ("0", 0)):
with pytest.raises(TypeError):
pix1[x, y]

for y in range(im1.size[1]):
for x in range(im1.size[0]):
pix2[x, y] = pix1[x, y]
Expand Down Expand Up @@ -109,6 +118,13 @@ def test_sanity_negative_index(self):

assert_image_equal(im1, im2)

@pytest.mark.skipif(numpy is None, reason="NumPy not installed")
def test_numpy(self):
im = hopper()
pix = im.load()

assert pix[numpy.int32(1), numpy.int32(2)] == (18, 20, 59)


class TestImageGetPixel(AccessTest):
@staticmethod
Expand Down
14 changes: 12 additions & 2 deletions src/_imaging.c
Expand Up @@ -1109,7 +1109,12 @@ _getxy(PyObject *xy, int *x, int *y) {
} else if (PyFloat_Check(value)) {
*x = (int)PyFloat_AS_DOUBLE(value);
} else {
goto badval;
PyObject *int_value = PyObject_CallMethod(value, "__int__", NULL);
if (int_value != NULL && PyLong_Check(int_value)) {
*x = PyLong_AS_LONG(int_value);
} else {
goto badval;
}
}

value = PyTuple_GET_ITEM(xy, 1);
Expand All @@ -1118,7 +1123,12 @@ _getxy(PyObject *xy, int *x, int *y) {
} else if (PyFloat_Check(value)) {
*y = (int)PyFloat_AS_DOUBLE(value);
} else {
goto badval;
PyObject *int_value = PyObject_CallMethod(value, "__int__", NULL);
if (int_value != NULL && PyLong_Check(int_value)) {
*y = PyLong_AS_LONG(int_value);
} else {
goto badval;
}
}

return 0;
Expand Down