Consider transparency when drawing text on an RGBA image

This commit is contained in:
Andrew Murray 2020-04-19 20:56:17 +10:00
parent a0d8e550ec
commit e10cab42f1
4 changed files with 19 additions and 3 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@ -236,7 +236,7 @@ class TestImagingPaste:
[ [
(127, 191, 254, 191), (127, 191, 254, 191),
(111, 207, 206, 110), (111, 207, 206, 110),
(127, 254, 127, 0), (255, 255, 255, 0) if mode == "RGBA" else (127, 254, 127, 0),
(207, 207, 239, 239), (207, 207, 239, 239),
(191, 191, 190, 191), (191, 191, 190, 191),
(207, 206, 111, 112), (207, 206, 111, 112),

View File

@ -150,6 +150,18 @@ class TestImageFont:
assert_image_equal(img_path, img_filelike) assert_image_equal(img_path, img_filelike)
def test_transparent_background(self):
im = Image.new(mode="RGBA", size=(300, 100))
draw = ImageDraw.Draw(im)
ttf = self.get_font()
txt = "Hello World!"
draw.text((10, 10), txt, font=ttf)
target = "Tests/images/transparent_background_text.png"
with Image.open(target) as target_img:
assert_image_similar(im, target_img, 4.09)
def test_textsize_equal(self): def test_textsize_equal(self):
im = Image.new(mode="RGB", size=(300, 100)) im = Image.new(mode="RGB", size=(300, 100))
draw = ImageDraw.Draw(im) draw = ImageDraw.Draw(im)

View File

@ -379,9 +379,13 @@ fill_mask_L(Imaging imOut, const UINT8* ink, Imaging imMask,
UINT8* mask = (UINT8*) imMask->image[y+sy]+sx; UINT8* mask = (UINT8*) imMask->image[y+sy]+sx;
for (x = 0; x < xsize; x++) { for (x = 0; x < xsize; x++) {
for (i = 0; i < pixelsize; i++) { for (i = 0; i < pixelsize; i++) {
*out = BLEND(*mask, *out, ink[i], tmp1); UINT8 channel_mask = *mask;
out++; if (strcmp(imOut->mode, "RGBA") == 0 && i != 3) {
channel_mask = 255 - (255 - channel_mask) * (1 - (255 - out[3]) / 255);
}
out[i] = BLEND(channel_mask, out[i], ink[i], tmp1);
} }
out += pixelsize;
mask++; mask++;
} }
} }