diff --git a/Tests/test_image_access.py b/Tests/test_image_access.py index a4d7847e60c..5c700131c6a 100644 --- a/Tests/test_image_access.py +++ b/Tests/test_image_access.py @@ -252,6 +252,14 @@ def test_putpixel_type_error2(self, mode: str) -> None: ): im.putpixel((0, 0), v) # type: ignore[arg-type] + def test_putpixel_type_error_float(self) -> None: + im = hopper("F") + for v in ("foo", None): + with pytest.raises( + TypeError, match="color must be int, float or single-element tuple" + ): + im.putpixel((0, 0), v) # type: ignore[arg-type] + @pytest.mark.parametrize("mode", IMAGE_MODES1 + IMAGE_MODES2) def test_putpixel_overflow_error(self, mode: str) -> None: im = hopper(mode) diff --git a/Tests/test_image_convert.py b/Tests/test_image_convert.py index 74e242e6473..fa7cc6e764c 100644 --- a/Tests/test_image_convert.py +++ b/Tests/test_image_convert.py @@ -96,6 +96,22 @@ def test_16bit_workaround() -> None: _test_float_conversion(im.convert("I")) +@pytest.mark.parametrize( + "value, expected", + ( + (2147483648, 2147483647), + (2147483647, 2147483647), + (1, 1), + (-5.5, -5), + (-2147483648, -2147483648), + (-2147483649, -2147483648), + ), +) +def test_f_to_i(value: float, expected: int) -> None: + im = Image.new("F", (1, 1), value) + assert im.convert("I").getpixel((0, 0)) == expected + + def test_opaque() -> None: alpha = hopper("P").convert("PA").getchannel("A") diff --git a/src/_imaging.c b/src/_imaging.c index 8644d10a067..fb1c2d1777e 100644 --- a/src/_imaging.c +++ b/src/_imaging.c @@ -688,6 +688,12 @@ getink(PyObject *color, Imaging im, char *ink) { return ink; case IMAGING_TYPE_FLOAT32: /* floating point */ + if (!PyFloat_Check(color) && !PyLong_Check(color)) { + PyErr_SetString( + PyExc_TypeError, "color must be int, float or single-element tuple" + ); + return NULL; + } f = PyFloat_AsDouble(color); if (f == -1.0 && PyErr_Occurred()) { return NULL; diff --git a/src/libImaging/Convert.c b/src/libImaging/Convert.c index 2d0df72063c..be98af44d29 100644 --- a/src/libImaging/Convert.c +++ b/src/libImaging/Convert.c @@ -672,7 +672,7 @@ f2i(UINT8 *out_, const UINT8 *in_, int xsize) { FLOAT32 f; INT32 i; memcpy(&f, in_, sizeof(f)); - i = f; + i = f >= INT32_MAX ? INT32_MAX : (f >= INT32_MIN ? (INT32)f : INT32_MIN); memcpy(out_, &i, sizeof(i)); } }