Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
124 changes: 124 additions & 0 deletions Tests/test_imagedraw.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import os.path
import random

import pytest

Expand Down Expand Up @@ -1846,3 +1847,126 @@ 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


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))
24 changes: 24 additions & 0 deletions docs/releasenotes/13.1.0.rst
Original file line number Diff line number Diff line change
Expand Up @@ -217,3 +217,27 @@ BLP2 DXT images with a width of 1 or 2
BLP2 images using DXT1, DXT3 or DXT5 compression with a width of 1 or 2 pixels were
decoded incorrectly, and used up to four times more memory than needed while loading.
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.
16 changes: 9 additions & 7 deletions src/PIL/ImageDraw.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
79 changes: 46 additions & 33 deletions src/_imaging.c
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,11 @@
#include <math.h>
#include <stddef.h>

/* 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))
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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();

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand All @@ -3798,18 +3803,22 @@ _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 {
for (i = 0; i < n - 1; i++) {
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,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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,
Expand Down
Loading
Loading