initial
This commit is contained in:
95
CompressResizeImages.py
Executable file
95
CompressResizeImages.py
Executable file
@@ -0,0 +1,95 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# import sys
|
||||
import os
|
||||
from PIL import Image
|
||||
from resizeimage import resizeimage
|
||||
|
||||
|
||||
# save directory name
|
||||
directory_name = 'compress'
|
||||
|
||||
# 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)
|
||||
|
||||
with Image.open(filepath) as image:
|
||||
if resize and image.width >= size and image.width > image.height:
|
||||
print('resize and compress: ' + file)
|
||||
cover = resizeimage.resize_width(image, size)
|
||||
cover.save(
|
||||
str(final_path) + '/' + 'min-' + file,
|
||||
image.format,
|
||||
optimize=True,
|
||||
quality=quality,
|
||||
resample=Image.LANCZOS
|
||||
)
|
||||
elif resize and image.height >= size and image.height > image.width:
|
||||
print('resize and compress: ' + file)
|
||||
cover = resizeimage.resize_height(image, size)
|
||||
cover.save(
|
||||
str(final_path) + '/' + 'min-' + file,
|
||||
image.format,
|
||||
optimize=True,
|
||||
quality=quality,
|
||||
resample=Image.LANCZOS
|
||||
)
|
||||
else:
|
||||
print('compress: ' + file)
|
||||
image.save(
|
||||
str(final_path) + "/" + "min-" + file,
|
||||
image.format,
|
||||
optimize=True,
|
||||
quality=quality,
|
||||
resample=Image.LANCZOS
|
||||
)
|
||||
|
||||
|
||||
def main(quality_img, resize, size):
|
||||
# get current directory path
|
||||
cwd = os.getcwd()
|
||||
|
||||
# only support these 4 formats
|
||||
formats = ('.jpg', '.jpeg', '.png', '.webp')
|
||||
|
||||
# get all files
|
||||
for file in os.listdir(cwd):
|
||||
# check file and compress file
|
||||
if os.path.splitext(file)[1].lower() in formats:
|
||||
# call compress function
|
||||
compressor(file, quality_img, resize, size)
|
||||
|
||||
print("Done")
|
||||
|
||||
|
||||
# Driver code
|
||||
if __name__ == "__main__":
|
||||
size = 900
|
||||
# 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