import os
import sys
from PIL import Image
import io
i = 1
def calc_size(image, quality):
buffer = io.BytesIO()
image.save(buffer, format='JPEG', quality=quality)
return buffer.tell()
def find_quality(image, target_filesize):
lo = 0
hi = 100
mid = (lo + hi) // 2
actual_size = calc_size(image, mid)
while lo <= hi:
mid = (lo + hi) // 2
actual_size = calc_size(image, mid)
if actual_size == target_filesize:
return mid
elif actual_size > target_filesize:
hi = mid - 1
else:
lo = mid + 1
return mid
def res_img(image, size, name, target_filesize, part):
image.thumbnail(size, Image.LANCZOS)
quality = find_quality(image, target_filesize)
filename = f'{name}-{part}-{i+1}.jpeg'
image.save(filename, format='JPEG', quality=quality, subsampling=0, optimize=True)
print(f'{filename} done.')
def main():
target_size = (4000, 4000)
target_filesize2 = 200 * 1024
part2 = 'KB'
for i, file in enumerate(os.listdir()):
if file.endswith('.jpeg') or file.endswith('.jpg'):
try:
image = Image.open(file)
if image.size != target_size:
image = image.resize(target_size)
name = file.split('-')[0]
res_img(image, target_size, name, target_filesize2, part2)
except Exception as e:
print(f'{e}')
if __name__ == '__main__':
main()