From e27efcba9868967ea0134db332cb467965d5a73f Mon Sep 17 00:00:00 2001 From: strike19 <26605353+strike19@users.noreply.github.com> Date: Wed, 11 Nov 2026 11:56:30 +0000 Subject: [PATCH 1/2] Make ImageDraw translation invariant at negative coordinates Fractional coordinates were converted with a C cast, which truncates towards zero, and ROUND_UP/ROUND_DOWN, lround() and roundf() round halves away from zero. Both treat the origin differently from every other position, so a shape extending past the left or top edge was drawn differently from the same shape moved by a whole number of pixels and then cropped. * _imaging.c: convert coordinates with floor() in arc, bitmap, chord, ellipse, line, point, pieslice, polygon and rectangle, so this also applies to lines and outlines drawn with dash. * Draw.c: round scanline edges with halves towards +inf (ROUND_RIGHT/ ROUND_LEFT) instead of symmetric around zero; the symmetric macros stay for wide line offsets, which are differences of coordinates. Use floor for outline edges, curve flattening and transforms, and for the pieslice outline and clip tree. * Draw.c: compute the x of an edge on a scanline from exact integer numerators in double precision, instead of float dx * dy. Whether a pixel is set at an integer-coordinate polygon edge no longer depends on float error. * ImageDraw.py: round rounded_rectangle() corners half up, and split the text position with floor so the fractional part is always in [0, 1). For coordinates >= 0, output only changes for rounded_rectangle() at a coordinate halfway between two integers, such as 2.5 (previously rounded half to even), and for edges of polygons, regular polygons, wide lines and outlines that float error put on the wrong side of a pixel. Fixes #10228 Co-Authored-By: Claude Sonnet 5.5 --- Tests/test_imagedraw.py | 107 +++++++++++++++++++++++++++++++++++ docs/releasenotes/13.1.0.rst | 24 ++++++++ src/PIL/ImageDraw.py | 16 +++--- src/_imaging.c | 79 +++++++++++++++----------- src/libImaging/Draw.c | 84 +++++++++++++++++---------- 5 files changed, 240 insertions(+), 70 deletions(-) diff --git a/Tests/test_imagedraw.py b/Tests/test_imagedraw.py index 28c965c562b..787a1afec74 100644 --- a/Tests/test_imagedraw.py +++ b/Tests/test_imagedraw.py @@ -1,6 +1,7 @@ from __future__ import annotations import os.path +import random import pytest @@ -1846,3 +1847,109 @@ def test_dash_empty() -> None: with pytest.raises(ValueError, match="dash must be a non-empty tuple of ints"): draw.rectangle([10, 10, 90, 90], dash=()) + + +def _random_shapes(rng: random.Random, n: int) -> list[tuple[float, ...]]: + return [tuple(rng.uniform(-30, 70) for _ in range(8)) for _ in range(n)] + + +def _draw_shape( + draw: ImageDraw.ImageDraw, kind: str, c: tuple[float, ...], dx: float +) -> None: + pts = [(c[i] + dx, c[i + 1] + dx) for i in range(0, 8, 2)] + x0, y0 = min(pts[0][0], pts[1][0]), min(pts[0][1], pts[1][1]) + x1, y1 = max(pts[0][0], pts[1][0]), max(pts[0][1], pts[1][1]) + box = (x0, y0, x1, y1) + if kind == "line": + draw.line(pts[:2], 255) + elif kind == "wide line": + draw.line(pts[:3], 255, 5) + elif kind == "curve joint": + draw.line(pts[:3], 255, 9, "curve") + elif kind == "polygon": + draw.polygon(pts, 255) + elif kind == "polygon outline": + draw.polygon(pts, None, 255, 3) + elif kind == "regular_polygon": + draw.regular_polygon((x0 + 15, y0 + 15, 15), 5, 10, 255) + elif kind == "point": + draw.point(pts, 255) + elif kind == "rectangle": + draw.rectangle(box, 255) + elif kind == "rectangle outline": + draw.rectangle(box, None, 255, 3) + elif kind == "rounded_rectangle": + draw.rounded_rectangle(box, 4, 255) + elif kind == "ellipse": + draw.ellipse(box, 255) + elif kind == "ellipse outline": + draw.ellipse(box, None, 255, 3) + elif kind == "arc": + draw.arc(box, 20, 250, 255, 3) + elif kind == "chord": + draw.chord(box, 20, 250, 255) + elif kind == "pieslice": + draw.pieslice(box, 20, 250, 255) + elif kind == "pieslice outline": + draw.pieslice(box, 20, 250, None, 255, 3) + elif kind == "bitmap": + draw.bitmap((x0, y0), Image.new("1", (5, 5), 1), 255) # type: ignore[arg-type] + elif kind == "dash line": + draw.line(pts[:3], 255, dash=(4, 2)) + elif kind == "dash polygon outline": + draw.polygon(pts, None, 255, dash=(3, 1, 1, 1)) + elif kind == "dash rectangle outline": + draw.rectangle(box, None, 255, dash=(5, 3)) + + +SHAPE_KINDS = ( + "line", + "wide line", + "curve joint", + "polygon", + "polygon outline", + "regular_polygon", + "point", + "rectangle", + "rectangle outline", + "rounded_rectangle", + "ellipse", + "ellipse outline", + "arc", + "chord", + "pieslice", + "pieslice outline", + "bitmap", + "dash line", + "dash polygon outline", + "dash rectangle outline", +) + + +@pytest.mark.parametrize("kind", SHAPE_KINDS) +@pytest.mark.parametrize("shift", (10, 63)) +@pytest.mark.parametrize("integer", (False, True)) +def test_translation_invariant(kind: str, shift: int, integer: bool) -> None: + # Drawing a shape and then moving it by a whole number of pixels + # should give the same pixels as drawing it where it is + rng = random.Random(1) + size = 64 + for c in _random_shapes(rng, 60): + if integer: + c = tuple(float(round(v)) for v in c) + + im = Image.new("L", (size, size)) + _draw_shape(ImageDraw.Draw(im), kind, c, 0) + + moved = Image.new("L", (size + shift, size + shift)) + _draw_shape(ImageDraw.Draw(moved), kind, c, shift) + moved = moved.crop((shift, shift, shift + size, shift + size)) + + assert im.tobytes() == moved.tobytes(), (kind, c) + + +def test_rectangle_negative_half_pixel() -> None: + # A shape at (-1, -1, 0, 0) covers the pixel (0, 0) only + im = Image.new("L", (1, 1)) + ImageDraw.Draw(im).rectangle((-1, -1, 0, 0), 255) + assert im.getpixel((0, 0)) == 255 diff --git a/docs/releasenotes/13.1.0.rst b/docs/releasenotes/13.1.0.rst index 22759b2fc72..45e1749bfa7 100644 --- a/docs/releasenotes/13.1.0.rst +++ b/docs/releasenotes/13.1.0.rst @@ -196,3 +196,27 @@ Memory leak when merging a single band with a mismatched mode requested mode, such as ``Image.merge("F", [l_image])``, raised :py:exc:`ValueError` but leaked the memory allocated for the output image. This has been fixed. + +Drawing at negative coordinates +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:py:mod:`~PIL.ImageDraw` converted fractional coordinates to integers by truncating +towards zero, and rounded halves away from zero. Both treat the origin differently to +every other position, so a shape that extended past the left or top edge of an image +was drawn differently from the same shape moved by a whole number of pixels and then +cropped. + +Coordinates are now converted by rounding down, and halves are rounded towards positive +infinity, so that moving a shape by a whole number of pixels moves the drawn pixels by +the same amount. This includes lines and outlines drawn with ``dash``. + +This changes the output of all :py:mod:`~PIL.ImageDraw` methods for fractional +coordinates that are less than zero, including where a scanline meets an edge halfway +between two pixels. For coordinates greater than or equal to zero, the output only +changes for + +* :py:meth:`~PIL.ImageDraw.ImageDraw.rounded_rectangle` with a coordinate halfway + between two integers, such as 2.5. Its corners were rounded half to even, and are + now rounded half up. +* edges of polygons, regular polygons, wide lines and outlines that were previously + placed on the wrong side of a pixel by floating point error. diff --git a/src/PIL/ImageDraw.py b/src/PIL/ImageDraw.py index 210b76085ec..ab70dd9bd12 100644 --- a/src/PIL/ImageDraw.py +++ b/src/PIL/ImageDraw.py @@ -455,10 +455,12 @@ def rounded_rectangle( d = min(x1 - x0, y1 - y0, radius * 2) - x0 = round(x0) - y0 = round(y0) - x1 = round(x1) - y1 = round(y1) + # Round halves towards +inf, so that moving the rectangle by a whole + # number of pixels moves the drawn pixels by the same amount + x0 = math.floor(x0 + 0.5) + y0 = math.floor(y0 + 0.5) + x1 = math.floor(x1 + 0.5) + y1 = math.floor(y1 + 0.5) full_x, full_y = False, False if all(corners): full_x = d >= x1 - x0 - 1 @@ -626,9 +628,9 @@ def draw_text(ink: int, stroke_width: float = 0) -> None: mode = self.fontmode if stroke_width == 0 and image_text.embedded_color: mode = "RGBA" - x = int(line.x) - y = int(line.y) - start = (math.modf(line.x)[0], math.modf(line.y)[0]) + x = math.floor(line.x) + y = math.floor(line.y) + start = (line.x - x, line.y - y) if isinstance(image_text.font, ImageFont.FreeTypeFont): mask, offset = image_text.font.getmask2( line.text, diff --git a/src/_imaging.c b/src/_imaging.c index f6a29515269..19a15a95123 100644 --- a/src/_imaging.c +++ b/src/_imaging.c @@ -102,6 +102,11 @@ #include #include +/* Converts a drawing coordinate to the pixel that contains it. Truncating + * towards zero would make shapes at negative coordinates differ from the same + * shape moved by a whole number of pixels. */ +#define DRAW_COORD(v) ((int)floor(v)) + #define B16(p, i) ((((int)p[(i)]) << 8) + p[(i) + 1]) #define L16(p, i) ((((int)p[(i) + 1]) << 8) + p[(i)]) #define S16(v) ((v) < 32768 ? (v) : ((v) - 65536)) @@ -3571,10 +3576,10 @@ _draw_arc(ImagingDrawObject *self, PyObject *args) { Py_BEGIN_CRITICAL_SECTION2(self, self->image); n = ImagingDrawArc( self->image->image, - (int)xy[0], - (int)xy[1], - (int)xy[2], - (int)xy[3], + DRAW_COORD(xy[0]), + DRAW_COORD(xy[1]), + DRAW_COORD(xy[2]), + DRAW_COORD(xy[3]), start, end, &ink, @@ -3622,7 +3627,7 @@ _draw_bitmap_impl(ImagingDrawObject *self, PyObject *args) { // this unlocks self, so we've copied the critical bits to local. Py_BEGIN_CRITICAL_SECTION2(_image, bitmap); n = ImagingDrawBitmap( - _image->image, (int)xy[0], (int)xy[1], bitmap->image, &ink, blend + _image->image, DRAW_COORD(xy[0]), DRAW_COORD(xy[1]), bitmap->image, &ink, blend ); Py_END_CRITICAL_SECTION2(); @@ -3679,10 +3684,10 @@ _draw_chord(ImagingDrawObject *self, PyObject *args) { Py_BEGIN_CRITICAL_SECTION2(self, self->image); n = ImagingDrawChord( self->image->image, - (int)xy[0], - (int)xy[1], - (int)xy[2], - (int)xy[3], + DRAW_COORD(xy[0]), + DRAW_COORD(xy[1]), + DRAW_COORD(xy[2]), + DRAW_COORD(xy[3]), start, end, &ink, @@ -3737,10 +3742,10 @@ _draw_ellipse(ImagingDrawObject *self, PyObject *args) { Py_BEGIN_CRITICAL_SECTION2(self, self->image); n = ImagingDrawEllipse( self->image->image, - (int)xy[0], - (int)xy[1], - (int)xy[2], - (int)xy[3], + DRAW_COORD(xy[0]), + DRAW_COORD(xy[1]), + DRAW_COORD(xy[2]), + DRAW_COORD(xy[3]), &ink, fill, width, @@ -3783,10 +3788,10 @@ _draw_lines(ImagingDrawObject *self, PyObject *args) { p = &xy[i + i]; if (ImagingDrawLine( self->image->image, - (int)p[0], - (int)p[1], - (int)p[2], - (int)p[3], + DRAW_COORD(p[0]), + DRAW_COORD(p[1]), + DRAW_COORD(p[2]), + DRAW_COORD(p[3]), &ink, self->blend, dash, @@ -3798,7 +3803,11 @@ _draw_lines(ImagingDrawObject *self, PyObject *args) { } if (p) { /* draw last point */ ImagingDrawPoint( - self->image->image, (int)p[2], (int)p[3], &ink, self->blend + self->image->image, + DRAW_COORD(p[2]), + DRAW_COORD(p[3]), + &ink, + self->blend ); } } else { @@ -3806,10 +3815,10 @@ _draw_lines(ImagingDrawObject *self, PyObject *args) { double *p = &xy[i + i]; if (ImagingDrawWideLine( self->image->image, - (int)p[0], - (int)p[1], - (int)p[2], - (int)p[3], + DRAW_COORD(p[0]), + DRAW_COORD(p[1]), + DRAW_COORD(p[2]), + DRAW_COORD(p[3]), &ink, width, self->blend, @@ -3847,7 +3856,11 @@ _draw_points(ImagingDrawObject *self, PyObject *args) { for (i = 0; i < n; i++) { double *p = &xy[i + i]; if (ImagingDrawPoint( - self->image->image, (int)p[0], (int)p[1], &ink, self->blend + self->image->image, + DRAW_COORD(p[0]), + DRAW_COORD(p[1]), + &ink, + self->blend ) < 0) { free(xy); return NULL; @@ -3930,10 +3943,10 @@ _draw_pieslice(ImagingDrawObject *self, PyObject *args) { Py_BEGIN_CRITICAL_SECTION2(self, self->image); n = ImagingDrawPieslice( self->image->image, - (int)xy[0], - (int)xy[1], - (int)xy[2], - (int)xy[3], + DRAW_COORD(xy[0]), + DRAW_COORD(xy[1]), + DRAW_COORD(xy[2]), + DRAW_COORD(xy[3]), start, end, &ink, @@ -3990,8 +4003,8 @@ _draw_polygon(ImagingDrawObject *self, PyObject *args) { } for (i = 0; i < n; i++) { - ixy[i + i] = (int)xy[i + i]; - ixy[i + i + 1] = (int)xy[i + i + 1]; + ixy[i + i] = DRAW_COORD(xy[i + i]); + ixy[i + i + 1] = DRAW_COORD(xy[i + i + 1]); } free(xy); @@ -4058,10 +4071,10 @@ _draw_rectangle(ImagingDrawObject *self, PyObject *args) { Py_BEGIN_CRITICAL_SECTION2(self, self->image); n = ImagingDrawRectangle( self->image->image, - (int)xy[0], - (int)xy[1], - (int)xy[2], - (int)xy[3], + DRAW_COORD(xy[0]), + DRAW_COORD(xy[1]), + DRAW_COORD(xy[2]), + DRAW_COORD(xy[3]), &ink, fill, width, diff --git a/src/libImaging/Draw.c b/src/libImaging/Draw.c index b344aa4e05f..f7bf88144db 100644 --- a/src/libImaging/Draw.c +++ b/src/libImaging/Draw.c @@ -67,6 +67,16 @@ ink16(Imaging im, const void *ink_) { #define ROUND_UP(f) ((int)((f) >= 0.0 ? floor((f) + 0.5F) : -floor(fabs(f) + 0.5F))) #define ROUND_DOWN(f) ((int)((f) >= 0.0 ? ceil((f) - 0.5F) : -ceil(fabs(f) - 0.5F))) +/* + * Rounds to the nearest integer, with halves going towards +inf (RIGHT) or + * -inf (LEFT). Unlike ROUND_UP|DOWN, these are not symmetric around zero, so + * that drawing a shape and then moving it by a whole number of pixels gives + * the same pixels. Used for coordinates, where only the position matters; + * ROUND_UP|DOWN remain for offsets that are differences of coordinates. + */ +#define ROUND_RIGHT(f) ((int)floor((f) + 0.5)) +#define ROUND_LEFT(f) ((int)ceil((f) - 0.5)) + /* -------------------------------------------------------------------- */ /* Primitives */ /* -------------------------------------------------------------------- */ @@ -77,8 +87,23 @@ typedef struct { int x0, y0; int xmin, ymin, xmax, ymax; float dx; + int dxn, dyn; /* x1 - x0, y1 - y0 of the original segment */ } Edge; +/* + * x of the edge on scanline y. The numerator is an exact integer product, so + * the only rounding is that of one correctly rounded division. A result that is + * exactly halfway between two pixels is therefore exactly representable, and + * whether a pixel is set no longer depends on float error in `dx * dy`. + */ +static inline double +edge_x(const Edge *e, int y) { + if (e->dyn == 0) { + return e->x0; + } + return e->x0 + (double)((long long)(y - e->y0) * e->dxn) / e->dyn; +} + typedef void (*point_handler)(Imaging, int, int, int); /* Type used in "polygon*" functions */ @@ -395,7 +420,7 @@ line( static int x_cmp(const void *x0, const void *x1) { - float diff = *((float *)x0) - *((float *)x1); + double diff = *((double *)x0) - *((double *)x1); if (diff < 0) { return -1; } else if (diff > 0) { @@ -450,12 +475,12 @@ polygon_generic( Imaging im, int n, Edge *e, int ink, int eofill, hline_handler hline, Imaging mask ) { Edge **edge_table; - float *xx; + double *xx; int edge_count = 0; int ymin = im->ysize - 1; int ymax = 0; int i, j, k; - float adjacent_line_x, adjacent_line_x_other_edge; + double adjacent_line_x, adjacent_line_x_other_edge; if (n <= 0) { return 0; @@ -493,7 +518,7 @@ polygon_generic( /* Process the edge table with a scan line searching for intersections */ /* malloc check ok, using calloc */ - xx = calloc(edge_count * 2, sizeof(float)); + xx = calloc(edge_count * 2, sizeof(double)); if (!xx) { free(edge_table); return -1; @@ -503,7 +528,7 @@ polygon_generic( for (i = 0; i < edge_count; i++) { Edge *current = edge_table[i]; if (ymin >= current->ymin && ymin <= current->ymax) { - xx[j++] = (ymin - current->y0) * current->dx + current->x0; + xx[j++] = edge_x(current, ymin); if (ymin == current->ymax && ymin < ymax) { // Needed to draw consistent polygons @@ -520,26 +545,20 @@ polygon_generic( continue; } // Check if the two edges join to make a corner - if (roundf(xx[j - 1]) == - roundf( - (ymin - other_edge->y0) * other_edge->dx + - other_edge->x0 - )) { + if (ROUND_RIGHT(xx[j - 1]) == + ROUND_RIGHT(edge_x(other_edge, ymin))) { // Determine points from the edges on the next row // Or if this is the last row, check the previous row int offset = ymin == current->ymax ? -1 : 1; - adjacent_line_x = - (ymin + offset - current->y0) * current->dx + - current->x0; + adjacent_line_x = edge_x(current, ymin + offset); if (ymin + offset >= other_edge->ymin && ymin + offset <= other_edge->ymax) { adjacent_line_x_other_edge = - (ymin + offset - other_edge->y0) * other_edge->dx + - other_edge->x0; + edge_x(other_edge, ymin + offset); if (xx[j - 1] > adjacent_line_x + 1 && xx[j - 1] > adjacent_line_x_other_edge + 1) { xx[j - 1] = - roundf(fmax( + ROUND_RIGHT(fmax( adjacent_line_x, adjacent_line_x_other_edge )) + 1; @@ -548,7 +567,7 @@ polygon_generic( xx[j - 1] < adjacent_line_x_other_edge - 1 ) { xx[j - 1] = - roundf(fmin( + ROUND_RIGHT(fmin( adjacent_line_x, adjacent_line_x_other_edge )) - 1; @@ -560,11 +579,11 @@ polygon_generic( } } } - qsort(xx, j, sizeof(float), x_cmp); + qsort(xx, j, sizeof(double), x_cmp); if (hasAlpha == 1) { int x_pos = j == 0 ? -1 : 0; for (i = 1; i < j; i += 2) { - int x_end = ROUND_DOWN(xx[i]); + int x_end = ROUND_LEFT(xx[i]); if (x_end < x_pos) { // Line would be before the current position continue; @@ -575,7 +594,7 @@ polygon_generic( continue; } - int x_start = ROUND_UP(xx[i - 1]); + int x_start = ROUND_RIGHT(xx[i - 1]); if (x_pos > x_start) { // Line would be partway through x_pos, so increase the starting // point @@ -591,7 +610,9 @@ polygon_generic( draw_horizontal_lines(im, n, e, ink, &x_pos, ymin, hline, mask); } else { for (i = 1; i < j; i += 2) { - (*hline)(im, ROUND_UP(xx[i - 1]), ymin, ROUND_DOWN(xx[i]), ink, mask); + (*hline)( + im, ROUND_RIGHT(xx[i - 1]), ymin, ROUND_LEFT(xx[i]), ink, mask + ); } } } @@ -629,6 +650,8 @@ add_edge(Edge *e, int x0, int y0, int x1, int y1) { e->x0 = x0; e->y0 = y0; + e->dxn = x1 - x0; + e->dyn = y1 - y0; } typedef struct { @@ -1187,10 +1210,10 @@ clip_tree_do_clip( // X of intersection double ix = -(B * y + C) / A; if (A * x0 + B * y + C < eps) { - x0 = lround(fmax(x0, ix)); + x0 = ROUND_RIGHT(fmax(x0, ix)); } if (A * x1 + B * y + C < eps) { - x1 = lround(fmin(x1, ix)); + x1 = ROUND_RIGHT(fmin(x1, ix)); } } if (x0 <= x1) { @@ -1798,7 +1821,8 @@ ImagingDrawPieslice( if (pieSideNew(im, x0, y0, x1, y1, end, ink, width, op)) { return -1; } - int xc = lround((x0 + x1 - width) / 2.0), yc = lround((y0 + y1 - width) / 2.0); + int xc = ROUND_RIGHT((x0 + x1 - width) / 2.0), + yc = ROUND_RIGHT((y0 + y1 - width) / 2.0); ellipseNew(im, xc, yc, xc + width - 1, yc + width - 1, ink, 1, 0, op); return pieNew(im, x0, y0, x1, y1, start, end, ink, width, op); } @@ -1899,7 +1923,7 @@ ImagingOutlineLine(ImagingOutline outline, float x1, float y1) { return -1; /* out of memory */ } - add_edge(e, (int)outline->x, (int)outline->y, (int)x1, (int)y1); + add_edge(e, FLOOR(outline->x), FLOOR(outline->y), FLOOR(x1), FLOOR(y1)); outline->x = x1; outline->y = y1; @@ -1939,7 +1963,7 @@ ImagingOutlineCurve( float x = outline->x * u3 + 3 * (x1 * t * u2 + x2 * t2 * u) + x3 * t3 + 0.5; float y = outline->y * u3 + 3 * (y1 * t * u2 + y2 * t2 * u) + y3 * t3 + 0.5; - add_edge(e++, xo, yo, (int)x, (int)y); + add_edge(e++, FLOOR(xo), FLOOR(yo), FLOOR(x), FLOOR(y)); xo = x, yo = y; } @@ -2002,10 +2026,10 @@ ImagingOutlineTransform(ImagingOutline outline, double a[6]) { upgrade your compiler (make sure you have the right service pack) */ - X0 = (int)(a0 * x0 + a1 * y0 + a2); - Y0 = (int)(a3 * x0 + a4 * y0 + a5); - X1 = (int)(a0 * x1 + a1 * y1 + a2); - Y1 = (int)(a3 * x1 + a4 * y1 + a5); + X0 = FLOOR(a0 * x0 + a1 * y0 + a2); + Y0 = FLOOR(a3 * x0 + a4 * y0 + a5); + X1 = FLOOR(a0 * x1 + a1 * y1 + a2); + Y1 = FLOOR(a3 * x1 + a4 * y1 + a5); add_edge(eOut, X0, Y0, X1, Y1); From f7eca4e32f5ce1e53e6e4c37771b7ef05dcc20f3 Mon Sep 17 00:00:00 2001 From: strike19 <26605353+strike19@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:40:33 +0100 Subject: [PATCH 2/2] Flatten outline curves in double precision ImageDraw.Outline parsed its coordinates as float and flattened curves in float, so the rounding error depended on the position. A curve moved by a whole number of pixels could set different pixels, also with integer coordinates (e.g. when moved by 1000). Store and parse outline coordinates as double and flatten in double. Co-Authored-By: Claude Opus 5.5 --- Tests/test_imagedraw.py | 17 +++++++++++++++++ src/libImaging/Draw.c | 34 ++++++++++++++++++++-------------- src/libImaging/Imaging.h | 12 +++++++++--- src/outline.c | 12 ++++++------ 4 files changed, 52 insertions(+), 23 deletions(-) diff --git a/Tests/test_imagedraw.py b/Tests/test_imagedraw.py index 787a1afec74..2430d0ef53e 100644 --- a/Tests/test_imagedraw.py +++ b/Tests/test_imagedraw.py @@ -1953,3 +1953,20 @@ def test_rectangle_negative_half_pixel() -> None: im = Image.new("L", (1, 1)) ImageDraw.Draw(im).rectangle((-1, -1, 0, 0), 255) assert im.getpixel((0, 0)) == 255 + + +def test_shape_curve_translation_invariant() -> None: + # Curves are flattened in double precision, so that moving one by a whole + # number of pixels moves the drawn pixels by the same amount + def draw(shift: int) -> Image.Image: + outline = ImageDraw.Outline() + outline.move(28 + shift, 16 + shift) + outline.curve( + 35 + shift, -14 + shift, 9 + shift, 22 + shift, 33 + shift, 42 + shift + ) + outline.close() + im = Image.new("L", (48 + shift, 48 + shift)) + ImageDraw.Draw(im).shape(outline, 255) + return im.crop((shift, shift, shift + 48, shift + 48)) + + assert_image_equal(draw(0), draw(1000)) diff --git a/src/libImaging/Draw.c b/src/libImaging/Draw.c index f7bf88144db..b6f3dcaf3ac 100644 --- a/src/libImaging/Draw.c +++ b/src/libImaging/Draw.c @@ -1836,9 +1836,9 @@ ImagingDrawPieslice( itself */ struct ImagingOutlineInstance { - float x0, y0; + double x0, y0; - float x, y; + double x, y; int count; Edge *edges; @@ -1907,7 +1907,7 @@ allocate(ImagingOutline outline, int extra) { } int -ImagingOutlineMove(ImagingOutline outline, float x0, float y0) { +ImagingOutlineMove(ImagingOutline outline, double x0, double y0) { outline->x = outline->x0 = x0; outline->y = outline->y0 = y0; @@ -1915,7 +1915,7 @@ ImagingOutlineMove(ImagingOutline outline, float x0, float y0) { } int -ImagingOutlineLine(ImagingOutline outline, float x1, float y1) { +ImagingOutlineLine(ImagingOutline outline, double x1, double y1) { Edge *e; e = allocate(outline, 1); @@ -1933,11 +1933,17 @@ ImagingOutlineLine(ImagingOutline outline, float x1, float y1) { int ImagingOutlineCurve( - ImagingOutline outline, float x1, float y1, float x2, float y2, float x3, float y3 + ImagingOutline outline, + double x1, + double y1, + double x2, + double y2, + double x3, + double y3 ) { Edge *e; int i; - float xo, yo; + double xo, yo; #define STEPS 32 @@ -1952,16 +1958,16 @@ ImagingOutlineCurve( /* flatten the bezier segment */ for (i = 1; i <= STEPS; i++) { - float t = ((float)i) / STEPS; - float t2 = t * t; - float t3 = t2 * t; + double t = ((double)i) / STEPS; + double t2 = t * t; + double t3 = t2 * t; - float u = 1.0F - t; - float u2 = u * u; - float u3 = u2 * u; + double u = 1.0 - t; + double u2 = u * u; + double u3 = u2 * u; - float x = outline->x * u3 + 3 * (x1 * t * u2 + x2 * t2 * u) + x3 * t3 + 0.5; - float y = outline->y * u3 + 3 * (y1 * t * u2 + y2 * t2 * u) + y3 * t3 + 0.5; + double x = outline->x * u3 + 3 * (x1 * t * u2 + x2 * t2 * u) + x3 * t3 + 0.5; + double y = outline->y * u3 + 3 * (y1 * t * u2 + y2 * t2 * u) + y3 * t3 + 0.5; add_edge(e++, FLOOR(xo), FLOOR(yo), FLOOR(x), FLOOR(y)); diff --git a/src/libImaging/Imaging.h b/src/libImaging/Imaging.h index 2a2dfa86437..113926f7850 100644 --- a/src/libImaging/Imaging.h +++ b/src/libImaging/Imaging.h @@ -599,12 +599,18 @@ ImagingDrawOutline( ); extern int -ImagingOutlineMove(ImagingOutline outline, float x, float y); +ImagingOutlineMove(ImagingOutline outline, double x, double y); extern int -ImagingOutlineLine(ImagingOutline outline, float x, float y); +ImagingOutlineLine(ImagingOutline outline, double x, double y); extern int ImagingOutlineCurve( - ImagingOutline outline, float x1, float y1, float x2, float y2, float x3, float y3 + ImagingOutline outline, + double x1, + double y1, + double x2, + double y2, + double x3, + double y3 ); extern int ImagingOutlineTransform(ImagingOutline outline, double a[6]); diff --git a/src/outline.c b/src/outline.c index 94ff2b7ac2a..b106f5033ce 100644 --- a/src/outline.c +++ b/src/outline.c @@ -86,8 +86,8 @@ PyOutline_Create(PyObject *self, PyObject *args) { static PyObject * _outline_move(OutlineObject *self, PyObject *args) { - float x0, y0; - if (!PyArg_ParseTuple(args, "ff", &x0, &y0)) { + double x0, y0; + if (!PyArg_ParseTuple(args, "dd", &x0, &y0)) { return NULL; } @@ -98,8 +98,8 @@ _outline_move(OutlineObject *self, PyObject *args) { static PyObject * _outline_line(OutlineObject *self, PyObject *args) { - float x1, y1; - if (!PyArg_ParseTuple(args, "ff", &x1, &y1)) { + double x1, y1; + if (!PyArg_ParseTuple(args, "dd", &x1, &y1)) { return NULL; } @@ -110,8 +110,8 @@ _outline_line(OutlineObject *self, PyObject *args) { static PyObject * _outline_curve(OutlineObject *self, PyObject *args) { - float x1, y1, x2, y2, x3, y3; - if (!PyArg_ParseTuple(args, "ffffff", &x1, &y1, &x2, &y2, &x3, &y3)) { + double x1, y1, x2, y2, x3, y3; + if (!PyArg_ParseTuple(args, "dddddd", &x1, &y1, &x2, &y2, &x3, &y3)) { return NULL; }