-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add image compression feature to WechatComAppChannel to compress images larger than 10MB before uploading to WeChat server. The compression is done using the `compress_imgfile` function in `utils.py`. The `fsize` function is also added to `utils.py` to calculate the size of a file or buffer.
- Loading branch information
Showing
2 changed files
with
52 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
import io | ||
import os | ||
|
||
from PIL import Image | ||
|
||
|
||
def fsize(file): | ||
if isinstance(file, io.BytesIO): | ||
return file.getbuffer().nbytes | ||
elif isinstance(file, str): | ||
return os.path.getsize(file) | ||
elif hasattr(file, "seek") and hasattr(file, "tell"): | ||
pos = file.tell() | ||
file.seek(0, os.SEEK_END) | ||
size = file.tell() | ||
file.seek(pos) | ||
return size | ||
else: | ||
raise TypeError("Unsupported type") | ||
|
||
|
||
def compress_imgfile(file, max_size): | ||
if fsize(file) <= max_size: | ||
return file | ||
file.seek(0) | ||
img = Image.open(file) | ||
rgb_image = img.convert("RGB") | ||
quality = 95 | ||
while True: | ||
out_buf = io.BytesIO() | ||
rgb_image.save(out_buf, "JPEG", quality=quality) | ||
if fsize(out_buf) <= max_size: | ||
return out_buf | ||
quality -= 5 |