您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

57 行
1.6KB

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