Amazing-Python-Scripts
115 строк · 2.7 Кб
1# Import required Image library
2from PIL import Image, ImageDraw, ImageFont
3
4# Taking Input From user
5path = input("Input the path of the image: ")
6path = path.strip('""')
7im = Image.open(path)
8width, height = im.size
9
10# Taking input for the text
11text = input('Enter the text for the watermark: ')
12font = ImageFont.truetype('arial.ttf', 20)
13
14# Taking Input For the Position of the text
15print("To Specify the position of the text , enter a number between 1 to 5.\n")
16print("Enter\n 1 for Top Left \n 2 for Top Right \n 3 for Bottom Left \n 4 for Bottom Right \n 5 for Center")
17pos = int(input())
18
19
20# resize the image and
21# upscaling quality
22re_width = 500
23re_height = 500
24# The image upscaling quality
25r_img = im.resize((re_width, re_height), Image.LANCZOS)
26r_img.size
27
28# textwrap the lines
29
30
31def text_wrap(text, font, max_width):
32lines = []
33
34# If the text width is smaller than the image width, then
35# no need to split
36# just add it to the line list and return
37
38if font.getsize(text)[0] <= max_width:
39lines.append(text)
40
41else:
42# split the line on the basis of spaces to get words
43words = text.split(' ')
44i = 0
45# append every word to a line while its width is shorter than the image width
46while i < len(words):
47line = ''
48while i < len(words) and font.getsize(line + words[i])[0] <= max_width:
49line = line + words[i] + " "
50i += 1
51if not line:
52line = words[i]
53i += 1
54lines.append(line)
55return lines
56
57
58max_x = 250
59lines = text_wrap(text, font, max_x)
60# calculating the max height that a text can have
61line_height = font.getsize('hg')[1]
62
63# setting the x,y values for different positions
64x_min = (r_img.size[0] * 5) // 100
65if font.getsize(text)[0] < max_x:
66x_max = (r_img.size[0] - font.getsize(text)[0]) + 10
67
68else:
69x_max = (r_img.size[0] * 50) // 100
70
71
72# For image at top
73y_min = (r_img.size[1] * 4) // 100
74# For Image at Bottom
75y_max = (r_img.size[1] * 97) // 100
76y_max -= (len(lines)*line_height)
77
78
79if pos == 1:
80x_start = x_min
81y_start = y_min
82
83elif pos == 2:
84x_start = x_max
85y_start = y_min
86
87elif pos == 3:
88x_start = x_min
89y_start = y_max
90
91elif pos == 4:
92x_start = x_max
93y_start = y_max
94
95else:
96x_start = (r_img.size[0] * 40) // 100
97y_start = (r_img.size[0] * 50) // 100
98
99
100draw = ImageDraw.Draw(r_img)
101
102# x coordinate and y coordinate for the text position
103x = x_start
104y = y_start
105
106for line in lines:
107
108draw.text((x, y), line, fill='rgb(255,255,255)', font=font)
109
110y = y + line_height
111
112r_img.show()
113
114# Save watermarked image
115r_img.save('Test_Image.png')
116