added conversion to 8 bit

This commit is contained in:
2022-01-27 11:42:52 +01:00
parent 2c8dbe2718
commit 2da0872227

View File

@@ -5,6 +5,7 @@ import sys
import os
import getopt
from PIL import Image
from pixelate import pixelate
from resizeimage import resizeimage
@@ -15,44 +16,67 @@ def compressor(file, final_path, quality, resize, size):
# open image
with Image.open(filepath) as image:
# resize and compress landscape images
if resize and image.width >= size and image.width > image.height:
if resize and image.width >= size and image.width >= image.height:
# resize
print('resizing: ' + file)
cover = resizeimage.resize_width(image, size)
# convert to 8 bit (if possible)
print('converting to 8 bit: ' + file)
if cover.format in ['JPG', 'JPEG']:
# TODO: JPG + JPEG are not converted to 8 bit
cover = cover.quantize(colors=256, method=2).convert("RGB")
else:
cover = cover.quantize(colors=256, method=2)
# compress and save
print('compressing: ' + file)
cover.save(
str(final_path) + '/' + 'min-' + file,
image.format,
optimize=True,
quality=quality,
resample=Image.LANCZOS
)
# resize and compress portrait images
elif resize and image.height >= size and image.height > image.width:
elif resize and image.height >= size and image.height >= image.width:
# resize
print('resizing: ' + file)
cover = resizeimage.resize_height(image, size)
# convert to 8 bit (if possible)
print('converting to 8 bit: ' + file)
if cover.format in ['JPG', 'JPEG']:
# TODO: JPG + JPEG are not converted to 8 bit
cover = cover.quantize(colors=256, method=2).convert("RGB")
else:
cover = cover.quantize(colors=256, method=2)
# compress and save
print('compressing: ' + file)
cover.save(
str(final_path) + '/' + 'min-' + file,
image.format,
optimize=True,
quality=quality,
resample=Image.LANCZOS
)
# compress images
else:
# convert to 8 bit (if possible)
print('converting to 8 bit: ' + file)
if image.format in ['JPG', 'JPEG']:
# TODO: JPG + JPEG are not converted to 8 bit
image = image.quantize(colors=256, method=2).convert("RGB")
else:
image = image.quantize(colors=256, method=2)
# compress and save
print('compress: ' + file)
image.save(
str(final_path) + "/" + "min-" + file,
image.format,
optimize=True,
quality=quality,
resample=Image.LANCZOS
)
def usage():
print(f'Usage: {os.path.basename(__file__)} [-h|--help] [-r|--resize] [-q|--quality QUALITY] [-s|--size SIZE]')
print('Compress and optionally resize all images (jpg|jpeg|png|webp) in the current folder')
print('Compress and optionally resize all images (jpg|jpeg|png|webp|gif) in the current folder')
print(' -h | --help Prints this help')
print(' -r | --resize Set this to resize the images')
print(' -q | --quality QUALITY Specify the quality (1-100, default 80)')
@@ -107,7 +131,7 @@ def main(argv):
print(e)
# only support these 4 formats
formats = ('.jpg', '.jpeg', '.png', '.webp')
formats = ('.jpg', '.jpeg', '.png', '.webp', '.gif')
# get all files
for file in os.listdir(os.getcwd()):