1
+ from pathlib import Path
1
2
import random
2
3
from io import BytesIO
3
4
4
5
from PIL import Image , ImageDraw , ImageFont
5
6
7
+
6
8
def draw_text_with_outline (draw , position , text , font , text_colour , outline_colour ):
7
9
x , y = position
8
10
# Draw outline
@@ -40,22 +42,37 @@ def calculate_corners(img_w, img_h, text_bbox, margin) -> list:
40
42
41
43
return corners
42
44
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
+
43
61
def draw_corner_watermark (
44
62
image_bytes : BytesIO ,
45
63
text : str ,
46
- text_size : int = 14 ,
64
+ font_family : str = "Gidole-Regular.ttf" ,
47
65
margin : int = 24
48
66
) -> Image :
49
67
with Image .open (image_bytes ).convert ("RGBA" ) as base :
50
68
txt = Image .new ("RGBA" , base .size , (255 , 255 , 255 , 0 ))
51
69
52
- # try:
53
- # fnt = ImageFont.truetype('Arial.ttf', text_size)
54
- # except IOError:
55
- # fnt = ImageFont.load_default()
56
-
57
- fnt = ImageFont .load_default ()
58
70
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()
59
76
# calculate size of textbox
60
77
text_bbox = d .textbbox ((0 , 0 ), text , font = fnt )
61
78
# choose a random corner for the text
@@ -88,8 +105,18 @@ def add_watermark(image_content: bytes) -> BytesIO | None:
88
105
return None
89
106
90
107
buff = BytesIO ()
91
- buff .name = 'image .jpeg'
108
+ buff .name = 'image_x .jpeg'
92
109
image .save (buff , 'JPEG' )
93
110
buff .seek (0 )
94
111
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