Compare commits
5 Commits
b2a3242112
...
master
Author | SHA1 | Date | |
---|---|---|---|
485a2352c3 | |||
1526f7e217 | |||
2da0872227 | |||
2c8dbe2718 | |||
a4098b05c2 |
@@ -1,95 +1,130 @@
|
|||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
|
|
||||||
# import sys
|
import sys
|
||||||
import os
|
import os
|
||||||
|
import getopt
|
||||||
from PIL import Image
|
from PIL import Image
|
||||||
from resizeimage import resizeimage
|
from resizeimage import resizeimage
|
||||||
|
|
||||||
|
|
||||||
# save directory name
|
def compressor(file, final_path, quality, resize, size):
|
||||||
directory_name = 'compress'
|
# get filepath of image
|
||||||
|
|
||||||
# save directory name and full path
|
|
||||||
final_path = f"{os.getcwd()}/{directory_name}"
|
|
||||||
|
|
||||||
try:
|
|
||||||
# if save directory is exists
|
|
||||||
if 'compress' in os.listdir():
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
# save directory not exist
|
|
||||||
# create save directory
|
|
||||||
os.mkdir(final_path)
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print(e)
|
|
||||||
|
|
||||||
|
|
||||||
def compressor(file, quality, resize, size):
|
|
||||||
filepath = os.path.join(os.getcwd(), file)
|
filepath = os.path.join(os.getcwd(), file)
|
||||||
|
|
||||||
|
# open image
|
||||||
with Image.open(filepath) as image:
|
with Image.open(filepath) as image:
|
||||||
if resize and image.width >= size and image.width > image.height:
|
cover = image
|
||||||
print('resize and compress: ' + file)
|
# resize
|
||||||
cover = resizeimage.resize_width(image, size)
|
if resize:
|
||||||
cover.save(
|
print('resizing:' + file)
|
||||||
str(final_path) + '/' + 'min-' + file,
|
if cover.width >= size and cover.width >= cover.height:
|
||||||
image.format,
|
cover = resizeimage.resize_width(cover, size)
|
||||||
optimize=True,
|
elif cover.height >= size and cover.height >= cover.width:
|
||||||
quality=quality,
|
cover = resizeimage.resize_height(cover, size)
|
||||||
resample=Image.LANCZOS
|
|
||||||
)
|
# convert to 8 bit (if possible)
|
||||||
elif resize and image.height >= size and image.height > image.width:
|
print('converting to 8 bit: ' + file)
|
||||||
print('resize and compress: ' + file)
|
if cover.format in ['JPG', 'JPEG']:
|
||||||
cover = resizeimage.resize_height(image, size)
|
# TODO: JPG + JPEG are not converted to 8 bit
|
||||||
cover.save(
|
cover = cover.quantize(colors=256, method=2).convert("RGB")
|
||||||
str(final_path) + '/' + 'min-' + file,
|
|
||||||
image.format,
|
|
||||||
optimize=True,
|
|
||||||
quality=quality,
|
|
||||||
resample=Image.LANCZOS
|
|
||||||
)
|
|
||||||
else:
|
else:
|
||||||
print('compress: ' + file)
|
cover = cover.quantize(colors=256, method=2)
|
||||||
image.save(
|
|
||||||
str(final_path) + "/" + "min-" + file,
|
# compress and save
|
||||||
image.format,
|
print('compressing: ' + file)
|
||||||
optimize=True,
|
cover.save(
|
||||||
quality=quality,
|
str(final_path) + '/' + 'min-' + file,
|
||||||
resample=Image.LANCZOS
|
image.format,
|
||||||
)
|
optimize=True,
|
||||||
|
quality=quality,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def main(quality_img, resize, size):
|
def convert_to_webp(file, final_path):
|
||||||
# get current directory path
|
filepath = os.path.join(final_path, file)
|
||||||
cwd = os.getcwd()
|
|
||||||
|
|
||||||
# only support these 4 formats
|
with Image.open(filepath) as image:
|
||||||
formats = ('.jpg', '.jpeg', '.png', '.webp')
|
print('converting to webp: ' + file)
|
||||||
|
image.save(
|
||||||
|
str(final_path) + '/' + os.path.splitext(file)[0] + '.webp',
|
||||||
|
format="WEBP"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
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|gif) in the current folder')
|
||||||
|
print(' -h | --help Prints this help')
|
||||||
|
print(' -r | --resize Set this to resize the images')
|
||||||
|
print(' -c | --convert Set this to convert images to WEBP')
|
||||||
|
print(' -q | --quality QUALITY Specify the quality (1-100, default 80)')
|
||||||
|
print(' -s | --size SIZE Specify the size of the long side (default 900)')
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv):
|
||||||
|
# save arguments and options to variables
|
||||||
|
try:
|
||||||
|
opts, args = getopt.getopt(argv, 'hrcq:s:', ['help', 'resize', 'convert', 'quality=', 'size='])
|
||||||
|
except getopt.GetoptError as err:
|
||||||
|
print(err)
|
||||||
|
usage()
|
||||||
|
sys.exit(2)
|
||||||
|
|
||||||
|
# default values
|
||||||
|
quality_img = 80
|
||||||
|
resize = False
|
||||||
|
convert = False
|
||||||
|
size = 900
|
||||||
|
|
||||||
|
# parse arguments
|
||||||
|
for o, a in opts:
|
||||||
|
if o in ('-h', '--help'):
|
||||||
|
usage()
|
||||||
|
sys.exit()
|
||||||
|
elif o in ('-r', '--resize'):
|
||||||
|
resize = True
|
||||||
|
elif o in ('-c', '--convert'):
|
||||||
|
convert = True
|
||||||
|
elif o in ('-q', '--quality'):
|
||||||
|
quality_img = int(a)
|
||||||
|
elif o in ('-s', '--size'):
|
||||||
|
size = int(a)
|
||||||
|
else:
|
||||||
|
assert False, 'unhandled option'
|
||||||
|
|
||||||
|
# save directory name
|
||||||
|
directory_name = 'compress'
|
||||||
|
# save directory name and full path
|
||||||
|
final_path = f"{os.getcwd()}/{directory_name}"
|
||||||
|
|
||||||
|
try:
|
||||||
|
# if save directory exists
|
||||||
|
if directory_name in os.listdir():
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
# if save directory does not exist
|
||||||
|
# create save directory
|
||||||
|
os.mkdir(final_path)
|
||||||
|
except Exception as e:
|
||||||
|
print(e)
|
||||||
|
|
||||||
# get all files
|
# get all files
|
||||||
for file in os.listdir(cwd):
|
for file in os.listdir(os.getcwd()):
|
||||||
# check file and compress file
|
# check file and compress file
|
||||||
if os.path.splitext(file)[1].lower() in formats:
|
if os.path.splitext(file)[1].lower() in ('.jpg', '.jpeg', '.png', '.webp', '.gif'):
|
||||||
# call compress function
|
# call compress function
|
||||||
compressor(file, quality_img, resize, size)
|
compressor(file, final_path, quality_img, resize, size)
|
||||||
|
|
||||||
|
# convert to webp
|
||||||
|
if convert:
|
||||||
|
for file in os.listdir(final_path):
|
||||||
|
if os.path.splitext(file)[1].lower() in ('.jpg', '.jpeg', '.png', '.gif'):
|
||||||
|
convert_to_webp(file, final_path)
|
||||||
|
|
||||||
print("Done")
|
print("Done")
|
||||||
|
|
||||||
|
|
||||||
# Driver code
|
# Driver code
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
size = 900
|
main(sys.argv[1:])
|
||||||
# get image quality from user
|
|
||||||
quality_img = int(input("Enter image quality 1 to 100 (defaults to 80): ") or "80")
|
|
||||||
# check for resize
|
|
||||||
resize = str(input("Resize images? (N/y): ") or "N").lower()
|
|
||||||
if resize == 'n':
|
|
||||||
resize = False
|
|
||||||
elif resize == 'y':
|
|
||||||
resize = True
|
|
||||||
# get desired size
|
|
||||||
size = int(input("Size of longer side (defaults to 900): ") or "900")
|
|
||||||
|
|
||||||
main(quality_img, resize, size)
|
|
||||||
|
Reference in New Issue
Block a user