__init__.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # copyright (c) 2024 PaddlePaddle Authors. All Rights Reserve.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from pathlib import Path
  15. import PIL
  16. from PIL import ImageFont
  17. def get_font_file_path(file_name: str) -> str:
  18. """
  19. Get the path of the font file.
  20. Returns:
  21. str: The path to the font file.
  22. """
  23. return (Path(__file__).parent / file_name).resolve().as_posix()
  24. def create_font(txt: str, sz: tuple, font_path: str) -> ImageFont:
  25. """
  26. Create a font object with specified size and path, adjusted to fit within the given image region.
  27. Parameters:
  28. txt (str): The text to be rendered with the font.
  29. sz (tuple): A tuple containing the height and width of an image region, used for font size.
  30. font_path (str): The path to the font file.
  31. Returns:
  32. ImageFont: An ImageFont object adjusted to fit within the given image region.
  33. """
  34. font_size = int(sz[1] * 0.8)
  35. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  36. if int(PIL.__version__.split(".")[0]) < 10:
  37. length = font.getsize(txt)[0]
  38. else:
  39. length = font.getlength(txt)
  40. if length > sz[0]:
  41. font_size = int(font_size * sz[0] / length)
  42. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  43. return font
  44. PINGFANG_FONT_FILE_PATH = get_font_file_path("PingFang-SC-Regular.ttf")
  45. SIMFANG_FONT_FILE_PATH = get_font_file_path("simfang.ttf")