Skip to content

Commit b88bf72

Browse files
committed
added automatic text size selection
1 parent 9868f95 commit b88bf72

File tree

2 files changed

+36
-9
lines changed

2 files changed

+36
-9
lines changed

src/fonts/Gidole-Regular.ttf

77.1 KB
Binary file not shown.

src/storage/watermark.py

Lines changed: 36 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
from pathlib import Path
12
import random
23
from io import BytesIO
34

45
from PIL import Image, ImageDraw, ImageFont
56

7+
68
def draw_text_with_outline(draw, position, text, font, text_colour, outline_colour):
79
x, y = position
810
# Draw outline
@@ -40,22 +42,37 @@ def calculate_corners(img_w, img_h, text_bbox, margin) -> list:
4042

4143
return corners
4244

45+
def check_font_size(text, font_path, image, width_ratio):
46+
breakpoint = width_ratio * image.size[0]
47+
fontsize = 20
48+
learning_rate = 5
49+
font = ImageFont.truetype(font_path, fontsize)
50+
while True:
51+
if font.getlength(text) < breakpoint:
52+
fontsize += learning_rate
53+
else:
54+
learning_rate = learning_rate // 2
55+
fontsize -= learning_rate
56+
font = ImageFont.truetype(font_path, fontsize)
57+
if learning_rate <= 1:
58+
break
59+
return font
60+
4361
def draw_corner_watermark(
4462
image_bytes: BytesIO,
4563
text: str,
46-
text_size: int = 14,
64+
font_family: str = "Gidole-Regular.ttf",
4765
margin: int = 24
4866
) -> Image:
4967
with Image.open(image_bytes).convert("RGBA") as base:
5068
txt = Image.new("RGBA", base.size, (255, 255, 255, 0))
5169

52-
# try:
53-
# fnt = ImageFont.truetype('Arial.ttf', text_size)
54-
# except IOError:
55-
# fnt = ImageFont.load_default()
56-
57-
fnt = ImageFont.load_default()
5870
d = ImageDraw.Draw(txt)
71+
72+
width_ratio = .15 # Portion of the image the text width should be (between 0 and 1)
73+
font_path = str(Path(Path.home(), "src", "fonts", font_family))
74+
fnt = check_font_size(text, font_path, base, width_ratio)
75+
# fnt = ImageFont.load_default()
5976
# calculate size of textbox
6077
text_bbox = d.textbbox((0, 0), text, font=fnt)
6178
# choose a random corner for the text
@@ -88,8 +105,18 @@ def add_watermark(image_content: bytes) -> BytesIO | None:
88105
return None
89106

90107
buff = BytesIO()
91-
buff.name = 'image.jpeg'
108+
buff.name = 'image_x.jpeg'
92109
image.save(buff, 'JPEG')
93110
buff.seek(0)
94111

95-
return buff
112+
return buff#image
113+
114+
# if __name__ == '__main__':
115+
116+
# # image_path = Path(Path.home(), "src", "test1.jpeg") # Adjust the path if necessary
117+
# image_path = Path(Path.home(), "src", "test1.jpeg") # Adjust the path if necessary
118+
# with open(image_path, 'rb') as image_file:
119+
# image_bytes = image_file.read()
120+
# watermarked_image = add_watermark(image_bytes)
121+
# watermarked_image.save('/src/image_3x.jpg')
122+

0 commit comments

Comments
 (0)