Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

35 rindas
828B

  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