Merge branch 'master' of git@host.fluxility.com:optimg

Conflicts:
	trimage.py
This commit is contained in:
Kilian Valkhof 2010-02-02 19:54:54 +01:00
commit 6e1bf4138c
2 changed files with 164 additions and 132 deletions

View file

@ -3,174 +3,176 @@ from os import system
from os import listdir from os import listdir
from PyQt4.QtCore import * from PyQt4.QtCore import *
from PyQt4.QtGui import * from PyQt4.QtGui import *
from hurry.filesize import * from hurry.filesize import *
from optparse import OptionParser from optparse import OptionParser
from ui import Ui_trimage from ui import Ui_trimage
DEBUG = True
class StartQT4(QMainWindow): class StartQT4(QMainWindow):
def __init__(self, parent=None): def __init__(self, parent=None):
QWidget.__init__(self, parent) QWidget.__init__(self, parent)
self.ui = Ui_trimage() self.ui = Ui_trimage()
self.ui.setupUi(self) self.ui.setupUi(self)
self.quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self); # todo use standardKey Quit. self.quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self); # todo use standardKey Quit.
# set recompress to false # set recompress to false
self.ui.recompress.setEnabled(False) self.ui.recompress.setEnabled(False)
self.imagelist = [] self.imagelist = []
self.showapp = True self.showapp = True
# connect signals with slots # connect signals with slots
QObject.connect(self.ui.addfiles, SIGNAL("clicked()"), self.file_dialog) QObject.connect(self.ui.addfiles, SIGNAL("clicked()"), self.file_dialog)
QObject.connect(self.ui.recompress, SIGNAL("clicked()"), self.recompress_files) QObject.connect(self.ui.recompress, SIGNAL("clicked()"), self.recompress_files)
QObject.connect(self.quit_shortcut, SIGNAL("activated()"), qApp, SLOT('quit()')) QObject.connect(self.quit_shortcut, SIGNAL("activated()"), qApp, SLOT('quit()'))
parser = OptionParser(version="%prog 1.0", parser = OptionParser(version="%prog 1.0",
description="GUI front-end to compress png and jpg images via optipng and jpegoptim") description="GUI front-end to compress png and jpg images via optipng and jpegoptim")
parser.add_option("-f", "--file", parser.add_option("-f", "--file",
action="store", type="string", dest="filename", action="store", type="string", dest="filename",
help="image to compress") help="image to compress")
parser.add_option("-d", "--directory", parser.add_option("-d", "--directory",
action="store", type="string", dest="directory", action="store", type="string", dest="directory",
help="directory of images to compress") help="directory of images to compress")
(options, args) = parser.parse_args() (options, args) = parser.parse_args()
if options.filename: if options.filename:
self.file_from_cmd(options.filename) self.file_from_cmd(options.filename)
if options.directory: if options.directory:
self.dir_from_cmd(options.directory) self.dir_from_cmd(options.directory)
def dir_from_cmd(self, directory): def dir_from_cmd(self, directory):
self.showapp = False self.showapp = False
imagedir = listdir(directory) imagedir = listdir(directory)
for image in imagedir: for image in imagedir:
image = directory + "/" + image image = directory + "/" + image
name = QFileInfo(image).fileName() name = QFileInfo(image).fileName()
if self.checkname(name): if self.checkname(name):
self.compress_file(image) self.compress_file(image)
def file_from_cmd(self, image): def file_from_cmd(self, image):
self.showapp = False self.showapp = False
if self.checkname(name): if self.checkname(name):
self.compress_file(image) self.compress_file(image)
def file_drop(self): def file_drop(self):
print "booya" print "booya"
def checkname(self, filename): def checkname(self, filename):
if filename.endsWith("png") or filename.endsWith("jpg"): if filename.endsWith("png") or filename.endsWith("jpg"):
return True return True
def file_dialog(self): def file_dialog(self):
fd = QFileDialog(self) fd = QFileDialog(self)
images = fd.getOpenFileNames(self, images = fd.getOpenFileNames(self,
"Select one or more image files to compress", "Select one or more image files to compress",
"", # directory "", # directory
"Image files (*.png *.jpg)") "Image files (*.png *.jpg)")
for image in images: for image in images:
self.compress_file(image) self.compress_file(image)
def enable_recompress(self): def enable_recompress(self):
self.ui.recompress.setEnabled(True) self.ui.recompress.setEnabled(True)
def recompress_files(self): def recompress_files(self):
imagelistcopy = self.imagelist imagelistcopy = self.imagelist
self.imagelist = [] self.imagelist = []
for image in imagelistcopy: for image in imagelistcopy:
self.compress_file(image[-1]) self.compress_file(image[-1])
def compress_file(self, filename):
print filename
oldfile = QFileInfo(filename)
name = oldfile.fileName()
oldfilesize = oldfile.size()
oldfilesizestr = size(oldfilesize, system=alternative)
def compress_file(self, filename): if name.endsWith("jpg"):
oldfile = QFileInfo(filename) runstr = 'jpegoptim --strip-all -f "' + str(filename) + '"'
name = oldfile.fileName() runfile = system(runstr)
oldfilesize = oldfile.size()
oldfilesizestr = size(oldfilesize, system=alternative)
if name.endsWith("jpg"): elif name.endsWith("png"):
runstr = 'jpegoptim --strip-all -f "' + str(filename) + '"' #runstr = ('optipng -force -o7 "' + str(filename)
runfile = system(runstr) #+ '"; advpng -z4 "' + str(filename) + '"') ## don't do advpng yet
runstr = 'optipng -force -o7 "' + str(filename) + '"'
runfile = system(runstr)
elif name.endsWith("png"): if runfile == 0:
#runstr = 'optipng -force -o7 "' + str(filename) + '"; advpng -z4 "' + str(filename) + '"' ## don't do advpng yet newfile = QFile(filename)
runstr = 'optipng -force -o7 "' + str(filename) + '"' newfilesize = newfile.size()
runfile = system(runstr) newfilesizestr = size(newfilesize, system=alternative)
if runfile == 0: ratio = 100 - (float(newfilesize) / float(oldfilesize) * 100)
newfile = QFile(filename) ratiostr = "%.1f%%" % ratio
newfilesize = newfile.size()
newfilesizestr = size(newfilesize, system=alternative)
ratio = 100 - (float(newfilesize) / float(oldfilesize) * 100) self.imagelist.append(
ratiostr = "%.1f%%" % ratio (name, oldfilesizestr, newfilesizestr, ratiostr, filename))
self.update_table()
self.imagelist.append((name, oldfilesizestr, newfilesizestr, ratiostr, filename)) else:
self.update_table() print "uh. not good" #throw dialogbox error or something?
else: def update_table(self):
print "uh. not good" #throw dialogbox error or something? tview = self.ui.processedfiles
# set table model
tmodel = tri_table_model(self, self.imagelist,
['Filename', 'Old Size', 'New Size', 'Compressed'])
tview.setModel(tmodel)
def update_table(self): # set minimum size of table
tview = self.ui.processedfiles vh = tview.verticalHeader()
vh.setVisible(False)
# set table model # set horizontal header properties
tmodel = tri_table_model(self, hh = tview.horizontalHeader()
self.imagelist, hh.setStretchLastSection(True)
['Filename', 'Old Size', 'New Size', 'Compressed'])
tview.setModel(tmodel)
# set minimum size of table # set all row heights
vh = tview.verticalHeader() nrows = len(self.imagelist)
vh.setVisible(False) for row in range(nrows):
tview.setRowHeight(row, 25)
# set horizontal header properties tview.setColumnWidth(0, 300)
hh = tview.horizontalHeader() #tview.setDragDropMode(QAbstractItemView.DropOnly)
hh.setStretchLastSection(True) #tview.setAcceptDrops(True)
self.enable_recompress()
# set all row heights
nrows = len(self.imagelist)
for row in range(nrows):
tview.setRowHeight(row, 25)
tview.setColumnWidth(0,300)
tview.setDragDropMode(QAbstractItemView.DropOnly)
tview.setAcceptDrops(True)
self.enable_recompress()
class tri_table_model(QAbstractTableModel): class tri_table_model(QAbstractTableModel):
def __init__(self, parent, imagelist, header, *args):
"""
mydata is list of tuples
header is list of strings
tuple length has to match header length
"""
QAbstractTableModel.__init__(self, parent, *args)
self.imagelist = imagelist
self.header = header
def rowCount(self, parent): def __init__(self, parent, imagelist, header, *args):
return len(self.imagelist) """
mydata is list of tuples
header is list of strings
tuple length has to match header length
"""
QAbstractTableModel.__init__(self, parent, *args)
self.imagelist = imagelist
self.header = header
def columnCount(self, parent): def rowCount(self, parent):
return len(self.header) return len(self.imagelist)
def data(self, index, role): def columnCount(self, parent):
if not index.isValid(): return len(self.header)
return QVariant()
elif role != Qt.DisplayRole:
return QVariant()
return QVariant(self.imagelist[index.row()][index.column()])
def headerData(self, col, orientation, role): def data(self, index, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole: if not index.isValid():
return QVariant(self.header[col]) return QVariant()
return QVariant() elif role != Qt.DisplayRole:
return QVariant()
return QVariant(self.imagelist[index.row()][index.column()])
def headerData(self, col, orientation, role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return QVariant(self.header[col])
return QVariant()
if __name__ == "__main__": if __name__ == "__main__":

40
ui.py
View file

@ -8,6 +8,36 @@
# WARNING! All changes made in this file will be lost! # WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QUrl, QString
import trimage
class TrimageTableView(QtGui.QTableView):
def __init__(self, parent=None):
super(TrimageTableView, self).__init__(parent)
self.setAcceptDrops(True)
def dragEnterEvent(self, event):
if event.mimeData().hasFormat("text/uri-list"):
if trimage.DEBUG:
print("Accepting event: %s" % list(event.mimeData().formats()))
event.accept()
else:
if trimage.DEBUG:
print("Rejecting event: %s" % list(event.mimeData().formats()))
event.ignore()
def dragMoveEvent(self, event):
event.accept()
def dropEvent(self, event):
files = str(event.mimeData().data("text/uri-list")).strip().split()
for i, file in enumerate(files):
files[i] = QUrl(QString(file)).toLocalFile()
if trimage.DEBUG:
for file in files:
print("Drop received: %s" % file)
class Ui_trimage(object): class Ui_trimage(object):
def setupUi(self, trimage): def setupUi(self, trimage):
@ -88,18 +118,18 @@ class Ui_trimage(object):
self.horizontalLayout.addWidget(self.recompress) self.horizontalLayout.addWidget(self.recompress)
self.verticalLayout_2.addLayout(self.horizontalLayout) self.verticalLayout_2.addLayout(self.horizontalLayout)
self.processedfiles = QtGui.QTableView(self.frame) self.processedfiles = TrimageTableView(self.frame)
self.processedfiles.setEnabled(True) self.processedfiles.setEnabled(True)
self.processedfiles.setAcceptDrops(True) # self.processedfiles.setAcceptDrops(True)
self.processedfiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly) # self.processedfiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
self.processedfiles.setFrameShape(QtGui.QFrame.NoFrame) self.processedfiles.setFrameShape(QtGui.QFrame.NoFrame)
self.processedfiles.setFrameShadow(QtGui.QFrame.Plain) self.processedfiles.setFrameShadow(QtGui.QFrame.Plain)
self.processedfiles.setLineWidth(0) self.processedfiles.setLineWidth(0)
self.processedfiles.setMidLineWidth(0) self.processedfiles.setMidLineWidth(0)
self.processedfiles.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) self.processedfiles.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.processedfiles.setTabKeyNavigation(True) self.processedfiles.setTabKeyNavigation(True)
self.processedfiles.setDragEnabled(False) # self.processedfiles.setDragEnabled(True)
self.processedfiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly) # self.processedfiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
self.processedfiles.setAlternatingRowColors(True) self.processedfiles.setAlternatingRowColors(True)
self.processedfiles.setTextElideMode(QtCore.Qt.ElideRight) self.processedfiles.setTextElideMode(QtCore.Qt.ElideRight)
self.processedfiles.setShowGrid(True) self.processedfiles.setShowGrid(True)