__init__.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  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_pingfang_file_path():
  18. """get pingfang font file path"""
  19. return (Path(__file__).parent / "PingFang-SC-Regular.ttf").resolve().as_posix()
  20. def create_font(txt, sz, font_path):
  21. """create font"""
  22. font_size = int(sz[1] * 0.8)
  23. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  24. if int(PIL.__version__.split(".")[0]) < 10:
  25. length = font.getsize(txt)[0]
  26. else:
  27. length = font.getlength(txt)
  28. if length > sz[0]:
  29. font_size = int(font_size * sz[0] / length)
  30. font = ImageFont.truetype(font_path, font_size, encoding="utf-8")
  31. return font
  32. PINGFANG_FONT_FILE_PATH = get_pingfang_file_path()