Skip to content

Instantly share code, notes, and snippets.

@florianfelix
Created August 21, 2018 10:50
Show Gist options
  • Save florianfelix/44af663a999fa8ab4f34678b3e1e42dd to your computer and use it in GitHub Desktop.
Save florianfelix/44af663a999fa8ab4f34678b3e1e42dd to your computer and use it in GitHub Desktop.
imagemackick batch operations
import os
import sys
from subprocess import run
import logging
logger = logging.getLogger('convert_to_jpg')
hdlr = logging.FileHandler('%s.log' % (__file__), mode="w")
formatter = logging.Formatter('>> %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
log = logger.debug
def get_paths(args):
if not args:
return None, None
dirpath = os.path.dirname(args[0])
imgpaths = [f for f in args if f.lower().endswith('.jpg') or f.endswith('.png')]
pdfpaths = [f for f in args if f.lower().endswith('.pdf')]
return dirpath, imgpaths, pdfpaths
def get_command(source, target):
command = ['convert']
command.append(source)
command.extend('-sampling-factor 4:2:0'.split(' '))
command.append('-strip')
command.extend('-quality 85'.split(' '))
command.extend('-interlace JPEG'.split(' '))
command.extend('-colorspace RGB'.split(' '))
command.append(target)
return command
def convert_images(dirpath, imgpaths):
savepath = os.path.join(dirpath, 'optimized')
if not os.path.exists(savepath):
os.makedirs(savepath)
log('Optimizing Images in %s' % (dirpath))
success = []
failed = []
for img in imgpaths:
imgname = os.path.basename(img)
imgname = imgname.rsplit('.')[0] + '.jpg'
imgname = imgname.replace(' ', '-')
imgtarget = os.path.join(savepath, imgname)
try:
command = get_command(img, imgtarget)
run(command)
if os.path.exists(imgtarget):
success.append(imgtarget)
else:
failed.append(imgtarget)
except Exception as e:
log('EXCEPTION %s' % (os.path.basename(img)))
log(e)
failed.append(imgtarget)
for f in success:
log(f)
log('FAILED %d:' % (len(failed)))
log('OPTIMIZED %d:' % (len(success)))
for f in failed:
log(f)
def convert_pdfs(dirpath, pdfpaths):
for pdf in pdfpaths:
name = os.path.basename(pdf).rsplit('.')[0]
log('extracting %s' % name)
savepath = os.path.join(dirpath, name + '_jpg')
if not os.path.exists(savepath):
os.makedirs(savepath)
log('Optimizing PDF in %s' % (dirpath))
try:
target = os.path.basename(pdf)
target = target.rsplit('.')[0] + '.jpg'
target = target.replace(' ', '_')
target = os.path.join(savepath, target)
command = get_command(pdf, target)
run(command)
except Exception as e:
log('EXCEPTION %s' % (os.path.basename(pdf)))
log(e)
def main():
dirpath, imgpaths, pdfpaths = get_paths(sys.argv[1:])
if imgpaths:
convert_images(dirpath, imgpaths)
if pdfpaths:
convert_pdfs(dirpath, pdfpaths)
if __name__ == '__main__':
main()
from subprocess import run
import os
from pprint import pprint
def optimize_jpg(root, files):
print('Optimizing %d Files'%(len(files)))
for f in files:
path = os.path.join(root, f)
tdir = os.path.join(root, 'optimized')
if not os.path.exists(tdir):
os.makedirs(tdir)
tpath = os.path.join(tdir, f)
tpath = tpath.rsplit('.')[0] + '.jpg'
print('Optimizing: %s'%path)
command = 'convert %s -sampling-factor 4:2:0 -strip -quality 85 -interlace JPEG -colorspace Gray/sRGB %s' %(path, tpath)
run(command.split(' '))
return tdir
def resize_to_width(root, files, width=400):
for f in files:
path = os.path.join(root, f)
tdir = os.path.join(root, 'resized')
if not os.path.exists(tdir):
os.makedirs(tdir)
tpath = os.path.join(tdir, f)
print('Resizing to width %d: %s' %(width, path))
resize_command = 'convert %s -resize %dx5000 %s' %(path, width, tpath)
run(resize_command.split(' '))
return tdir
def main():
path = '/home/felix/Documents/60_wz_local/images/product_images/info_images/'
for root, dirs, files in os.walk(path):
jpgs = [f for f in files if f.endswith('.jpg') or f.endswith('.png')]
#optimize_jpg(root, jpgs)
resize_to_width(root, jpgs, 260)
#only one folder deep, else comment the break
break
if __name__ == '__main__':
main()
import os
from subprocess import run
from tkinter import *
import logging
logger = logging.getLogger('convert_to_jpg')
hdlr = logging.FileHandler('%s.log' %__file__, mode="w")
formatter = logging.Formatter('>> %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.DEBUG)
log = logger.debug
def isintable(d):
try:
d = int(d)
# log('%d is intable' %d)
return True
except:
# log('%s is not intable' %d)
return False
def get_command(source, width, target):
command = ['convert']
command.append(source)
command.append('-resize')
command.append('%dx9000' %width)
# command.extend('-sampling-factor 4:2:0'.split(' '))
command.append('-strip')
command.extend('-quality 85'.split(' '))
command.extend('-interlace JPEG'.split(' '))
# command.extend('-colorspace RGB'.split(' '))
command.append(target)
return command
def resize_to_width(root, files, width=400):
for f in files:
fname = os.path.basename(f)
path = os.path.join(root, f)
tdir = os.path.join(root, 'resized')
if not os.path.exists(tdir):
os.makedirs(tdir)
tpath = os.path.join(tdir, fname)
print('Resizing to width %d: %s' %(width, path))
log('Resizing to width %d: %s' %(width, path))
resize_command = get_command(path, width, tpath)
e = run(resize_command)
def walk_files(width):
if not isintable(width):
return
width = int(width)
files = sys.argv[1:]
files = [f for f in files if f.lower().endswith('.jpg') or f.lower().endswith('.png')]
if not files:
log('No Files, Aborting')
# files = ['/home/felix/Documents/image/HM/werbebilder/aussenwerbung/final/test/t_jpg/t-0.jpg']
return
resize_to_width(os.path.dirname(files[0]), files, width)
return
def main():
log(sys.argv)
master = Tk()
# Text field
e = Entry(master)
e.pack()
e.focus_set()
def enter(event):
callback()
def callback():
data = e.get()
walk_files(width=data)
quit()
# OK Button
b = Button(master, text="OK", width=10, command=callback)
b.pack()
# Key Bindings
master.bind("<Return>", enter)
master.bind("<KP_Enter>", enter)
mainloop()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment