Created
July 19, 2022 06:49
-
-
Save sangwin/353c34790d701f9ee62eded9fc7e466e to your computer and use it in GitHub Desktop.
Compress images in a folder using TinyPNG plugin in Python
This file contains hidden or 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
import tinify | |
import os | |
tinify.key = "API_KEY" | |
arr = os.listdir('uncompressed') | |
arrLen = len(arr) | |
// GET SIZE OF THE DIRECTORIES | |
def get_size(start_path = '.'): | |
total_size = 0 | |
for dirpath, dirnames, filenames in os.walk(start_path): | |
for f in filenames: | |
fp = os.path.join(dirpath, f) | |
# skip if it is symbolic link | |
if not os.path.islink(fp): | |
total_size += os.path.getsize(fp) | |
return total_size | |
// LOOP IMAGES ONE BY ONE | |
for x in arr: | |
print('------------------------------') | |
filename, file_extension = os.path.splitext(x) | |
print(filename + ' processing...') | |
print(str(arrLen) + ' remaining') | |
source = tinify.from_file("uncompressed/"+x) // COMPRESS IMAGE | |
source.to_file("compressed/"+x) // SAVE COMPRESSED IMAGE | |
arrLen = arrLen - 1 | |
// PRINT DIFFERENCE OF SIZES | |
uncompressed = get_size('uncompressed') | |
compressed = get_size('compressed') | |
print('Uncompressed Size : ', get_size('uncompressed'), 'bytes') | |
print('Compressed Size : ', get_size('compressed'), 'bytes') | |
print('####### YOU SAVED ', uncompressed - compressed, ' BYTES ###############') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment