comment trimage

This commit is contained in:
Kilian Valkhof 2010-02-02 21:49:11 +01:00
parent abedbc5bdd
commit d23e6a4b68
2 changed files with 43 additions and 10 deletions

1
todo
View file

@ -24,7 +24,6 @@ optipng for png and gif, jpegoptim for jpeg. both are available in ubuntu as dep
========================================== ==========================================
todo app wise todo app wise
- implement drag and drop on table - implement drag and drop on table
- clean up code, make it PEP-8
- implement threading (and include advpng then) - implement threading (and include advpng then)
- errors need to go to standarderror - errors need to go to standarderror
- test with filenames in spaces (probably works already) - test with filenames in spaces (probably works already)

View file

@ -18,13 +18,21 @@ class StartQT4(QMainWindow):
QWidget.__init__(self, parent) QWidget.__init__(self, parent)
self.ui = Ui_trimage() self.ui = Ui_trimage()
self.ui.setupUi(self) self.ui.setupUi(self)
# todo use standardKey Quit. #TODO use standardKey Quit.
self.quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self) self.quit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
# set recompress to false
# disable recompress
self.ui.recompress.setEnabled(False) self.ui.recompress.setEnabled(False)
# init imagelist
self.imagelist = [] self.imagelist = []
# show application on load (or not if there are command line options)
self.showapp = True self.showapp = True
# activate command line options
self.commandline_options()
# connect signals with slots # connect signals with slots
QObject.connect(self.ui.addfiles, SIGNAL("clicked()"), QObject.connect(self.ui.addfiles, SIGNAL("clicked()"),
self.file_dialog) self.file_dialog)
@ -33,25 +41,27 @@ class StartQT4(QMainWindow):
QObject.connect(self.quit_shortcut, SIGNAL("activated()"), QObject.connect(self.quit_shortcut, SIGNAL("activated()"),
qApp, SLOT('quit()')) qApp, SLOT('quit()'))
def commandline_options(self):
"""Set up the command line options."""
parser = OptionParser(version="%prog 1.0", parser = OptionParser(version="%prog 1.0",
description="GUI front-end to compress png and jpg images via " description="GUI front-end to compress png and jpg images via "
"optipng and jpegoptim") "optipng and jpegoptim")
parser.add_option("-f", "--file", action="store", type="string", parser.add_option("-f", "--file", action="store", type="string",
dest="filename", help="image to compress") dest="filename", help="image to compress")
parser.add_option("-d", "--directory", action="store", type="string", parser.add_option("-d", "--directory", action="store", type="string",
dest="directory", help="directory of images to compress") dest="directory", help="directory of images to compress")
options, args = parser.parse_args() options, args = parser.parse_args()
# do something with the file or directory
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):
"""Read the files in the directory and send all files to
compress_file."""
self.showapp = False self.showapp = False
imagedir = listdir(directory) imagedir = listdir(directory)
for image in imagedir: for image in imagedir:
@ -61,18 +71,22 @@ class StartQT4(QMainWindow):
self.compress_file(image) self.compress_file(image)
def file_from_cmd(self, image): def file_from_cmd(self, image):
"""Get the file and send it to compress_file"""
self.showapp = False self.showapp = False
if self.checkname(image): if self.checkname(image):
self.compress_file(image) self.compress_file(image)
def file_drop(self): def file_drop(self, files):
#TODO implement file drop handling
print("booya") print("booya")
def checkname(self, name): def checkname(self, name):
"""Check if the file is a jpg or png."""
if path.splitext(str(name))[1].lower() in [".jpg", ".jpeg", ".png"]: if path.splitext(str(name))[1].lower() in [".jpg", ".jpeg", ".png"]:
return True return True
def file_dialog(self): def file_dialog(self):
"""Open a file dialog and send the selected images to compress_file."""
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",
@ -83,47 +97,58 @@ class StartQT4(QMainWindow):
self.compress_file(image) self.compress_file(image)
def enable_recompress(self): def enable_recompress(self):
"""Enable the recompress button."""
self.ui.recompress.setEnabled(True) self.ui.recompress.setEnabled(True)
def recompress_files(self): def recompress_files(self):
"""Send each file in the current file list to compress_file again."""
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): def compress_file(self, filename):
print(filename) """Compress the given file, get data from it and call update_table."""
#gather old file data
oldfile = QFileInfo(filename) oldfile = QFileInfo(filename)
name = oldfile.fileName() name = oldfile.fileName()
oldfilesize = oldfile.size() oldfilesize = oldfile.size()
oldfilesizestr = size(oldfilesize, system=alternative) oldfilesizestr = size(oldfilesize, system=alternative)
#decide with tool to use
if path.splitext(str(filename))[1].lower() in [".jpg", ".jpeg"]: if path.splitext(str(filename))[1].lower() in [".jpg", ".jpeg"]:
runstr = 'jpegoptim --strip-all -f "' + str(filename) + '"' runstr = 'jpegoptim --strip-all -f "' + str(filename) + '"'
runfile = system(runstr) runfile = system(runstr)
elif path.splitext(str(filename))[1].lower() in [".png"]: elif path.splitext(str(filename))[1].lower() in [".png"]:
# don't do advpng yet
#runstr = ('optipng -force -o7 "' + str(filename) #runstr = ('optipng -force -o7 "' + str(filename)
#+ '"; advpng -z4 "' + str(filename) + '"') ## don't do advpng yet #+ '"; advpng -z4 "' + str(filename) + '"')
runstr = 'optipng -force -o7 "' + str(filename) + '"' runstr = 'optipng -force -o7 "' + str(filename) + '"'
runfile = system(runstr) runfile = system(runstr)
if runfile == 0: if runfile == 0:
#gather new file data
newfile = QFile(filename) newfile = QFile(filename)
newfilesize = newfile.size() newfilesize = newfile.size()
newfilesizestr = size(newfilesize, system=alternative) newfilesizestr = size(newfilesize, system=alternative)
#calculate ratio and make a nice string
ratio = 100 - (float(newfilesize) / float(oldfilesize) * 100) ratio = 100 - (float(newfilesize) / float(oldfilesize) * 100)
ratiostr = "%.1f%%" % ratio ratiostr = "%.1f%%" % ratio
# append current image to list
self.imagelist.append( self.imagelist.append(
(name, oldfilesizestr, newfilesizestr, ratiostr, filename)) (name, oldfilesizestr, newfilesizestr, ratiostr, filename))
self.update_table() self.update_table()
else: else:
print("uh. not good") #throw dialogbox error or something? # TODO nice error recovery
print("uh. not good")
def update_table(self): def update_table(self):
"""Update the table view with the latest file data."""
tview = self.ui.processedfiles tview = self.ui.processedfiles
# set table model # set table model
@ -143,7 +168,11 @@ class StartQT4(QMainWindow):
nrows = len(self.imagelist) nrows = len(self.imagelist)
for row in range(nrows): for row in range(nrows):
tview.setRowHeight(row, 25) tview.setRowHeight(row, 25)
# set the first column to be longest
tview.setColumnWidth(0, 300) tview.setColumnWidth(0, 300)
# enable recompress button
self.enable_recompress() self.enable_recompress()
@ -160,12 +189,15 @@ class TriTableModel(QAbstractTableModel):
self.header = header self.header = header
def rowCount(self, parent): def rowCount(self, parent):
"""Count the number of rows."""
return len(self.imagelist) return len(self.imagelist)
def columnCount(self, parent): def columnCount(self, parent):
"""Count the number of columns."""
return len(self.header) return len(self.header)
def data(self, index, role): def data(self, index, role):
"""Get data."""
if not index.isValid(): if not index.isValid():
return QVariant() return QVariant()
elif role != Qt.DisplayRole: elif role != Qt.DisplayRole:
@ -173,6 +205,7 @@ class TriTableModel(QAbstractTableModel):
return QVariant(self.imagelist[index.row()][index.column()]) return QVariant(self.imagelist[index.row()][index.column()])
def headerData(self, col, orientation, role): def headerData(self, col, orientation, role):
"""Get header data."""
if orientation == Qt.Horizontal and role == Qt.DisplayRole: if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return QVariant(self.header[col]) return QVariant(self.header[col])
return QVariant() return QVariant()
@ -183,6 +216,7 @@ if __name__ == "__main__":
myapp = StartQT4() myapp = StartQT4()
if myapp.showapp: if myapp.showapp:
# no command line options called
myapp.show() myapp.show()
else: else:
quit() quit()