123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286 |
- from PIL import Image, ImageDraw, ImageFont
- import os
- def create_name(name,img_url,output_path):
-
- font : ImageFont
- image1 = Image.open(img_url).convert('RGBA')
- if detect_language(name) == "English":
- font = ImageFont.truetype(f"{os.path.split(os.path.abspath('main.py'))[0]}/static/MasaFont-Regular.ttf", 120, encoding="utf-8")
- if len(name) > 50:
- return "超過字數限制"
-
- # 設定初始位置
- x_position = 0
- y_position = 0
- max_width = int(font.getlength(name[0])*len(name))
- max_height = int(font.getlength(name[0])*len(name))
- image = Image.new('RGBA', (max_width,max_height), (255, 255, 255, 0))
- draw = ImageDraw.Draw(image)
- text_width = draw.textlength(name[0], font=font)
- for char in name:
- draw.text((x_position, y_position), char, font=font, fill=(0, 0, 0))
- x_position += text_width
- image1.paste(image, (500, 1500),image)
- # 保存疊加後的圖片
- image1.save(output_path)
- else:
- # 選擇中文字型和大小
- font = ImageFont.truetype(f"{os.path.split(os.path.abspath('main.py'))[0]}/static/MasaFont-Regular.ttf", 150, encoding="utf-8")
- if len(name) > 5 :
- return "超過字數限制"
- # 設定初始位置
- x_position = 0
- y_position = 0
- max_width = int(font.getlength(name[0]))
- max_height = int(font.getlength(name[0])*len(name))
- image = Image.new('RGBA', (max_width,max_height), (255, 255, 255, 0))
- draw = ImageDraw.Draw(image)
- text_width = draw.textlength(name[0], font=font)
- for char in name:
- draw.text((x_position, y_position), char, font=font, fill=(0, 0, 0))
- y_position += text_width
- image1.paste(image, (150, 900),image)
- # 保存疊加後的圖片
- image1.save(output_path)
-
- def create_image(text, output_path, font_size=300, bg_color=(255, 255, 255), text_color=(0, 0, 0), max_width=200):
-
- # 查看語言
- lines : list
- check_tag = "en"
- font : ImageFont
- if detect_language(text) == "English":
- font = ImageFont.truetype(f"{os.path.split(os.path.abspath('main.py'))[0]}/static/MasaFont-Regular.ttf", 200, encoding="utf-8")
- if len(text) > 80:
- return "超過字數限制"
- lines = split_text_by_length(text, 15)
- check_tag = "en"
- else:
- # 選擇中文字型和大小
- font = ImageFont.truetype(f"{os.path.split(os.path.abspath('main.py'))[0]}/static/MasaFont-Regular.ttf", font_size, encoding="utf-8")
- if len(text) > 15 :
- return "超過字數限制"
- lines = split_chinese_text(text, max_length=4)
- check_tag = "ch"
- # 設定初始位置
- x_position = 0
- y_position = 0
- lines_tmp = [x.strip() for x in lines if x.strip()!='']
- lines = lines_tmp
- print(lines)
-
- line_height = font.getlength(text[0])
- print(line_height)
- max_width = int(font.getlength(text[0])*len(lines))
- max_height = int(font.getlength(text[0])*find_longest_segment(lines))
- print(max_width,max_height)
-
- if check_tag == "en" :
- tmp = max_width
- max_width = max_height
- max_height = tmp*2
- # 建立一個白色背景的圖片
- image = Image.new('RGBA', (max_width,max_height), (255, 255, 255, 0))
- draw = ImageDraw.Draw(image)
- line_num = 0
- text_width = draw.textlength(lines[0][0], font=font)
-
- if check_tag == "en" :
- y_position = 0
- # 繪製每一行文字
- for line in lines:
-
- x_position = 0
- for char in line:
-
- draw.text((x_position, y_position), char, font=font, fill=text_color)
- x_position += text_width
- y_position += line_height +50
- line_num += 1
- else :
- x_position = max_width - text_width
- # 繪製每一行文字
- for line in lines:
-
- y_position = 0
- for char in line:
-
- draw.text((x_position, y_position), char, font=font, fill=text_color)
- y_position += text_width
- x_position -= line_height
- line_num += 1
- # 儲存圖片
- image.save(output_path)
- return "成功製作文字"
- def overlay_images(background_path, overlay_path, output_path,name):
- image1 = Image.open(background_path).convert('RGBA')
- image2 = Image.open(overlay_path).convert('RGBA')
- x = (image1.width - image2.width) // 2
- y = (image1.height - image2.height) // 2 - 160
- # 將第二張圖片疊加在第一張圖片上
- image1.paste(image2, (x, y),image2)
- # 保存疊加後的圖片
- image1.save(f"{output_path}_tmp.png")
-
- # 顯示疊加後的圖片
- # image1.show()
- print(f"finished, saving image at {output_path}")
- try:
- create_name(name,f"{output_path}_tmp.png",output_path)
- except Exception as e:
- print( str(e))
- im = Image.open(output_path)
- name =output_path.lower().split('/')[::-1][0]
- webp = name.replace('png', 'webp')
- im.save(f"{os.path.split(os.path.abspath('main.py'))[0]}/static/tendents/{webp}", 'WebP', quality=40, )
- os.remove(output_path)
- os.remove(f"{output_path}_tmp.png")
- def detect_language(text):
- for char in text:
- # Check if the character falls within the range of Chinese characters
- if '\u4e00' <= char <= '\u9fff':
- return 'Chinese'
- # If no Chinese characters are found, assume it's English
- return 'English'
- def split_text_by_length(text, length):
- paragraphs = []
- current_paragraph = ""
- words = text.split()
- for word in words:
- # If adding the current word exceeds the maximum length, start a new paragraph
- if len(current_paragraph) + len(word) + 1 > length:
- paragraphs.append(current_paragraph.strip())
- current_paragraph = ""
- # Add the current word to the current paragraph
- current_paragraph += word + " "
- # Add the remaining part as the last paragraph
- if current_paragraph:
- if current_paragraph.strip():
- paragraphs.append(current_paragraph.strip())
- #print(paragraphs)
- return paragraphs
- def split_chinese_text(text, max_length=5):
- """
- Split the Chinese text into segments with a maximum length.
- Args:
- text (str): The input Chinese text.
- max_length (int): The maximum length of each segment. Default is 5.
- Returns:
- list: A list of segments.
- """
- segments = []
- current_segment = ""
- for char in text:
- # 如果当前片段加上当前字符的长度超过最大长度,就添加当前片段到segments列表中,并且重置当前片段
- if len(current_segment) + len(char) > max_length:
- segments.append(current_segment)
- current_segment = ""
-
- # 如果当前字符不是空格,就添加到当前片段中
- if char != ' ':
- current_segment += char
- else :
- segments.append(current_segment)
- current_segment = ""
- # 添加最后一个片段到segments列表中
- if current_segment:
-
- if current_segment.strip() and current_segment != '':
- segments.append(current_segment)
- return segments
- def find_longest_segment(segments):
- """
- Find the longest segment from the given list of segments.
- Args:
- segments (list): The list of segments.
- Returns:
- str: The longest segment.
- """
- longest_segment = ""
- max_length = 0
- for segment in segments:
- if len(segment) > max_length:
- longest_segment = segment
- max_length = len(segment)
- return len(longest_segment)
- if __name__ == "__main__":
- text = "心想事成 萬事如意"
- output_path = "tendents/vertical_chinese_text.png"
- create_image(text, output_path)
- print(f"圖片已儲存至 {output_path}")
- output_path = "combined_image.png"
- # 執行疊加
- overlay_images("tendentest.png", "vertical_chinese_text.png", output_path)
|