Skip to content

Commit e10cab4

Browse files
committed
Consider transparency when drawing text on an RGBA image
1 parent a0d8e55 commit e10cab4

4 files changed

Lines changed: 19 additions & 3 deletions

File tree

1.24 KB
Loading

Tests/test_image_paste.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -236,7 +236,7 @@ def test_color_mask_L(self):
236236
[
237237
(127, 191, 254, 191),
238238
(111, 207, 206, 110),
239-
(127, 254, 127, 0),
239+
(255, 255, 255, 0) if mode == "RGBA" else (127, 254, 127, 0),
240240
(207, 207, 239, 239),
241241
(191, 191, 190, 191),
242242
(207, 206, 111, 112),

Tests/test_imagefont.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,18 @@ def test_render_equal(self):
150150

151151
assert_image_equal(img_path, img_filelike)
152152

153+
def test_transparent_background(self):
154+
im = Image.new(mode="RGBA", size=(300, 100))
155+
draw = ImageDraw.Draw(im)
156+
ttf = self.get_font()
157+
158+
txt = "Hello World!"
159+
draw.text((10, 10), txt, font=ttf)
160+
161+
target = "Tests/images/transparent_background_text.png"
162+
with Image.open(target) as target_img:
163+
assert_image_similar(im, target_img, 4.09)
164+
153165
def test_textsize_equal(self):
154166
im = Image.new(mode="RGB", size=(300, 100))
155167
draw = ImageDraw.Draw(im)

src/libImaging/Paste.c

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -379,9 +379,13 @@ fill_mask_L(Imaging imOut, const UINT8* ink, Imaging imMask,
379379
UINT8* mask = (UINT8*) imMask->image[y+sy]+sx;
380380
for (x = 0; x < xsize; x++) {
381381
for (i = 0; i < pixelsize; i++) {
382-
*out = BLEND(*mask, *out, ink[i], tmp1);
383-
out++;
382+
UINT8 channel_mask = *mask;
383+
if (strcmp(imOut->mode, "RGBA") == 0 && i != 3) {
384+
channel_mask = 255 - (255 - channel_mask) * (1 - (255 - out[3]) / 255);
385+
}
386+
out[i] = BLEND(channel_mask, out[i], ink[i], tmp1);
384387
}
388+
out += pixelsize;
385389
mask++;
386390
}
387391
}

0 commit comments

Comments
 (0)