skylight.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. from PIL import Image, ImageDraw, ImageFont
  2. import os
  3. def create_image(text, output_path, font_size=300, bg_color=(255, 255, 255), text_color=(0, 0, 0), max_width=200):
  4. # 查看語言
  5. lines : list
  6. check_tag = "en"
  7. font : ImageFont
  8. if detect_language(text) == "English":
  9. font = ImageFont.truetype(f"{os.path.split(os.path.abspath('main.py'))[0]}/static/MasaFont-Regular.ttf", 200, encoding="utf-8")
  10. if len(text) > 80:
  11. return "超過字數限制"
  12. lines = split_text_by_length(text, 15)
  13. check_tag = "en"
  14. else:
  15. # 選擇中文字型和大小
  16. font = ImageFont.truetype(f"{os.path.split(os.path.abspath('main.py'))[0]}/static/MasaFont-Regular.ttf", font_size, encoding="utf-8")
  17. if len(text) > 15 :
  18. return "超過字數限制"
  19. lines = split_chinese_text(text, max_length=4)
  20. check_tag = "ch"
  21. # 設定初始位置
  22. x_position = 0
  23. y_position = 0
  24. line_height = font.getlength(text[0])
  25. print(line_height)
  26. max_width = int(font.getlength(text[0])*len(lines))
  27. max_height = int(font.getlength(text[0])*find_longest_segment(lines))
  28. print(max_width,max_height)
  29. print(lines)
  30. if check_tag == "en" :
  31. tmp = max_width
  32. max_width = max_height
  33. max_height = tmp*2
  34. # 建立一個白色背景的圖片
  35. image = Image.new('RGBA', (max_width,max_height), (255, 255, 255, 0))
  36. draw = ImageDraw.Draw(image)
  37. line_num = 0
  38. text_width = draw.textlength(lines[0][0], font=font)
  39. if check_tag == "en" :
  40. y_position = 0
  41. # 繪製每一行文字
  42. for line in lines:
  43. x_position = 0
  44. for char in line:
  45. draw.text((x_position, y_position), char, font=font, fill=text_color)
  46. x_position += text_width
  47. y_position += line_height +50
  48. line_num += 1
  49. else :
  50. x_position = max_width - text_width
  51. # 繪製每一行文字
  52. for line in lines:
  53. y_position = 0
  54. for char in line:
  55. draw.text((x_position, y_position), char, font=font, fill=text_color)
  56. y_position += text_width
  57. x_position -= line_height
  58. line_num += 1
  59. # 儲存圖片
  60. image.save(output_path)
  61. return "成功製作文字"
  62. def overlay_images(background_path, overlay_path, output_path):
  63. image1 = Image.open(background_path).convert('RGBA')
  64. image2 = Image.open(overlay_path).convert('RGBA')
  65. x = (image1.width - image2.width) // 2
  66. y = (image1.height - image2.height) // 2 - 160
  67. # 將第二張圖片疊加在第一張圖片上
  68. image1.paste(image2, (x, y),image2)
  69. # 保存疊加後的圖片
  70. image1.save(output_path)
  71. # 顯示疊加後的圖片
  72. # image1.show()
  73. print(f"finished, saving image at {output_path}")
  74. im = Image.open(output_path)
  75. name =output_path.lower().split('/')[::-1][0]
  76. webp = name.replace('png', 'webp')
  77. im.save(f"{os.path.split(os.path.abspath('main.py'))[0]}/static/tendents/{webp}", 'WebP', quality=40, )
  78. os.remove(output_path)
  79. def detect_language(text):
  80. for char in text:
  81. # Check if the character falls within the range of Chinese characters
  82. if '\u4e00' <= char <= '\u9fff':
  83. return 'Chinese'
  84. # If no Chinese characters are found, assume it's English
  85. return 'English'
  86. def split_text_by_length(text, length):
  87. paragraphs = []
  88. current_paragraph = ""
  89. words = text.split()
  90. for word in words:
  91. # If adding the current word exceeds the maximum length, start a new paragraph
  92. if len(current_paragraph) + len(word) + 1 > length:
  93. paragraphs.append(current_paragraph.strip())
  94. current_paragraph = ""
  95. # Add the current word to the current paragraph
  96. current_paragraph += word + " "
  97. # Add the remaining part as the last paragraph
  98. if current_paragraph:
  99. paragraphs.append(current_paragraph.strip())
  100. return paragraphs
  101. def split_chinese_text(text, max_length=5):
  102. """
  103. Split the Chinese text into segments with a maximum length.
  104. Args:
  105. text (str): The input Chinese text.
  106. max_length (int): The maximum length of each segment. Default is 5.
  107. Returns:
  108. list: A list of segments.
  109. """
  110. segments = []
  111. current_segment = ""
  112. for char in text:
  113. # 如果当前片段加上当前字符的长度超过最大长度,就添加当前片段到segments列表中,并且重置当前片段
  114. if len(current_segment) + len(char) > max_length:
  115. segments.append(current_segment)
  116. current_segment = ""
  117. # 如果当前字符不是空格,就添加到当前片段中
  118. if char != ' ':
  119. current_segment += char
  120. else :
  121. segments.append(current_segment)
  122. current_segment = ""
  123. # 添加最后一个片段到segments列表中
  124. if current_segment:
  125. segments.append(current_segment)
  126. return segments
  127. def find_longest_segment(segments):
  128. """
  129. Find the longest segment from the given list of segments.
  130. Args:
  131. segments (list): The list of segments.
  132. Returns:
  133. str: The longest segment.
  134. """
  135. longest_segment = ""
  136. max_length = 0
  137. for segment in segments:
  138. if len(segment) > max_length:
  139. longest_segment = segment
  140. max_length = len(segment)
  141. return len(longest_segment)
  142. if __name__ == "__main__":
  143. text = "心想事成 萬事如意"
  144. output_path = "tendents/vertical_chinese_text.png"
  145. create_image(text, output_path)
  146. print(f"圖片已儲存至 {output_path}")
  147. output_path = "combined_image.png"
  148. # 執行疊加
  149. overlay_images("tendentest.png", "vertical_chinese_text.png", output_path)