Skip to content

Instantly share code, notes, and snippets.

@HemantNegi
Created September 20, 2017 15:57
Show Gist options
  • Save HemantNegi/da8b77029e2c5cd8925213e427c3329f to your computer and use it in GitHub Desktop.
Save HemantNegi/da8b77029e2c5cd8925213e427c3329f to your computer and use it in GitHub Desktop.
Cron job to compress the images on a server
# sudo apt-get install jpegoptim
# sudo apt-get install optipng
# jpegoptim -m90 04/*.jpg
# optipng 02/sharp_ps2_8x6.png
import os
import time
import glob
from subprocess import call
from datetime import datetime, timedelta
from os.path import join, getsize
path = '/var/www/html/wordpress/wp-content/uploads'
DELETE_OLD_DAYS = 3
def get_old_dates(days=0):
for day in range(0, days):
yield datetime.now() - timedelta(days=day)
def cron_job():
for dat in get_old_dates(DELETE_OLD_DAYS):
dir_name = '%s/%s' % (path, dat.strftime('%Y/%m'))
try:
for filename in os.listdir(dir_name):
info = os.stat('%s/%s' % (dir_name, filename))
# get modified time.
tim = time.localtime(info.st_mtime)
if tim.tm_year == dat.year and tim.tm_mon == dat.month and tim.tm_mday == dat.day:
print tim.tm_year, dat.year, " ", tim.tm_mon, dat.month, " ", tim.tm_mday, dat.day
file_path = '%s/%s' % (dir_name, filename)
print file_path
ext = file_path.split('.')[-1].upper()
if ext in ['JPG', 'JPEG']:
call(["jpegoptim", "-m90", file_path])
if ext in ["PNG", "GIF", "BMP"]:
call(["optipng", file_path])
old = int((dat - timedelta(days=DELETE_OLD_DAYS + 1)).strftime('%s'))
os.utime(file_path, (old, old))
except OSError as ex:
# print ex
pass
def optimize_all():
for dp, dn, filenames in os.walk(path):
for fil in filenames:
file_path = os.path.join(dp, fil)
print file_path
ext = file_path.split('.')[-1].upper()
if ext in ['JPG', 'JPEG']:
call(["jpegoptim", "-m90", file_path])
call(["chown", "www-data:www-data", file_path])
call(["chmod", "664", file_path])
if ext in ["PNG", "GIF", "BMP"]:
call(["optipng", file_path])
call(["chown", "www-data:www-data", file_path])
call(["chmod", "664", file_path])
optimize_all()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment