52 Zeilen
1.5KB

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