You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

71 satır
2.0KB

  1. import io
  2. import os
  3. from urllib.parse import urlparse
  4. from PIL import Image
  5. from common.log import logger
  6. def fsize(file):
  7. if isinstance(file, io.BytesIO):
  8. return file.getbuffer().nbytes
  9. elif isinstance(file, str):
  10. return os.path.getsize(file)
  11. elif hasattr(file, "seek") and hasattr(file, "tell"):
  12. pos = file.tell()
  13. file.seek(0, os.SEEK_END)
  14. size = file.tell()
  15. file.seek(pos)
  16. return size
  17. else:
  18. raise TypeError("Unsupported type")
  19. def compress_imgfile(file, max_size):
  20. if fsize(file) <= max_size:
  21. return file
  22. file.seek(0)
  23. img = Image.open(file)
  24. rgb_image = img.convert("RGB")
  25. quality = 95
  26. while True:
  27. out_buf = io.BytesIO()
  28. rgb_image.save(out_buf, "JPEG", quality=quality)
  29. if fsize(out_buf) <= max_size:
  30. return out_buf
  31. quality -= 5
  32. def split_string_by_utf8_length(string, max_length, max_split=0):
  33. encoded = string.encode("utf-8")
  34. start, end = 0, 0
  35. result = []
  36. while end < len(encoded):
  37. if max_split > 0 and len(result) >= max_split:
  38. result.append(encoded[start:].decode("utf-8"))
  39. break
  40. end = min(start + max_length, len(encoded))
  41. # 如果当前字节不是 UTF-8 编码的开始字节,则向前查找直到找到开始字节为止
  42. while end < len(encoded) and (encoded[end] & 0b11000000) == 0b10000000:
  43. end -= 1
  44. result.append(encoded[start:end].decode("utf-8"))
  45. start = end
  46. return result
  47. def get_path_suffix(path):
  48. path = urlparse(path).path
  49. return os.path.splitext(path)[-1].lstrip('.')
  50. def convert_webp_to_png(webp_image):
  51. from PIL import Image
  52. try:
  53. webp_image.seek(0)
  54. img = Image.open(webp_image).convert("RGBA")
  55. png_image = io.BytesIO()
  56. img.save(png_image, format="PNG")
  57. png_image.seek(0)
  58. return png_image
  59. except Exception as e:
  60. logger.error(f"Failed to convert WEBP to PNG: {e}")
  61. raise