-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·461 lines (389 loc) · 18.3 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtNetwork import *
from PyQt4.Qt import *
import os
import sys
sys.path.append(os.getcwd())
import re
if not hasattr(sys, "frozen"):
os.popen("pyuic4 ui.ui -o ui.py").read()
os.popen("pyrcc4 res.qrc -o res_rc.py").read()
import ui
import imgsite
import tempfile
import traceback
from watermark import *
from ImageQt import ImageQt
from PIL import Image
#try:
#from QLCoverFlow import QLCoverFlow
#from QLCoverFlowItem import QLCoverFlowItem
# USE_COVERFLOW = True
#except:
# USE_COVERFLOW = False
USE_COVERFLOW = False
app = None
display_modes = ["list", "icon", "coverflow"]
def handle_exception(exc_type, exc_value, exc_traceback):
#filename, line, dummy, dummy = traceback.extract_tb(exc_traceback).pop()
#filename = os.path.basename(filename)
#error = "%s: %s" % (str(exc_type).split(".")[-1], exc_value)
error = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback)).replace("\n", "<br>")
QMessageBox.critical(None, "ERROR", "<b>%s</b> " % error )
class ImageUploader(QMainWindow):
def __init__(self, parent=None):
super(ImageUploader, self).__init__(parent)
self.ui = ui.Ui_MainWindow()
self.ui.setupUi(self)
self.displayIndex = 0
if USE_COVERFLOW:
self.coverFlow = QLCoverFlow(self.ui.tabImages)
#print dir(self.coverFlow)
self.coverFlow.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.coverFlow.setFocusPolicy(Qt.ClickFocus)
self.coverFlow.hide()
self.ui.gridlayout.addWidget(self.coverFlow, 0, 0, 1, 1)
#self.ui.hboxlayout.insertWidget(0, self.coverFlow)
reg = QRegExp("\\d*%")
val = QRegExpValidator(reg, self)
self.ui.watermarkX.setValidator(val)
self.ui.watermarkY.setValidator(val)
self.watermark = ""
self.lastDir = ""
self.codeList = []
tempfile.tempdir = tempfile.mkdtemp(prefix="pymguploader")
self.settings = QSettings(QSettings.IniFormat, QSettings.UserScope, "Pymguploader")
self.scanSite()
self.loadSettings()
self.connect(self.ui.btnAdd, SIGNAL("clicked()"), self.addClicked)
self.connect(self.ui.btnAddFolder, SIGNAL("clicked()"), self.addFolderClicked)
self.connect(self.ui.btnCancel, SIGNAL("clicked()"), self.cancelUpload)
self.connect(self.ui.btnRemove, SIGNAL("clicked()"), self.removeClicked)
self.connect(self.ui.btnUpload, SIGNAL("clicked()"), self.uploadClicked)
self.connect(self.ui.btnDelete, SIGNAL("clicked()"), self.deleteImages)
self.connect(self.ui.btnCopy, SIGNAL("clicked()"), self.copyBB)
self.connect(self.ui.btnDisplayMode, SIGNAL("clicked()"), self.changeDisplayMode)
self.connect(self.ui.pbAddWatermark, SIGNAL("clicked()"), self.addWatermark)
self.connect(self.ui.pbRemoveWatermark, SIGNAL("clicked()"), self.removeWatermark)
self.connect(self.ui.rbCustom, SIGNAL("toggled(bool)"), self.wmCustomToggled)
self.connect(self.ui.tabWidget_2, SIGNAL("currentChanged(int)"), self.tabChanged)
self.connect(self.ui.rbUpperLeft, SIGNAL("clicked()"), self.updateWatermarkPreview)
self.connect(self.ui.rbBottomLeft, SIGNAL("clicked()"), self.updateWatermarkPreview)
self.connect(self.ui.rbUpperRight, SIGNAL("clicked()"), self.updateWatermarkPreview)
self.connect(self.ui.rbBottomRight, SIGNAL("clicked()"), self.updateWatermarkPreview)
self.connect(self.ui.rbScaled, SIGNAL("clicked()"), self.updateWatermarkPreview)
self.connect(self.ui.rbTiled, SIGNAL("clicked()"), self.updateWatermarkPreview)
self.connect(self.ui.rbCustom, SIGNAL("clicked()"), self.updateWatermarkPreview)
self.connect(self.ui.watermarkX, SIGNAL("textChanged(QString)"), self.updateWatermarkPreview)
self.connect(self.ui.watermarkY, SIGNAL("textChanged(QString)"), self.updateWatermarkPreview)
self.connect(self.ui.spinOpacity, SIGNAL("valueChanged(double)"), self.updateWatermarkPreview)
self.connect(self.ui.spinImg, SIGNAL("valueChanged(int)"), self.updateList)
self.connect(self.ui.comboFormat, SIGNAL("currentIndexChanged(int)"), self.formatChanged)
def copyBB(self):
app.clipboard().setText(self.ui.textBBCode.toPlainText())
def changeDisplayMode(self, n=-1):
if n == -1:
s = len(display_modes)
n = self.displayIndex+1
if n >= s:
n = 0
if display_modes[n] == "coverflow":
if USE_COVERFLOW:
self.coverFlow.show()
self.ui.imgList.hide()
self.setCoverFlowSize()
else:
n = 0
if display_modes[n] == "list":
if USE_COVERFLOW:
self.coverFlow.hide()
self.ui.imgList.show()
self.ui.imgList.setViewMode(QListView.ListMode)
elif display_modes[n] == "icon":
if USE_COVERFLOW:
self.coverFlow.hide()
self.ui.imgList.show()
self.ui.imgList.setViewMode(QListView.IconMode)
self.displayIndex = n
def tabChanged(self, index):
if index == 1: #watermark tab
self.updateWatermarkPreview()
def deleteImages(self):
res = QMessageBox.question(self, "Warning", "Are you sure you want to delete these images?", QMessageBox.Ok |QMessageBox.Cancel)
if res == QMessageBox.Ok:
for i in xrange(0, self.ui.imgList.count()):
os.remove(str(self.ui.imgList.item(i).text()))
self.ui.imgList.clear()
if USE_COVERFLOW:
self.coverFlow.clear()
def addFolderClicked(self):
fDir = QFileDialog.getExistingDirectory(self, "Select Directory", self.lastDir)
if not fDir:
return
filters = QStringList()
for f in ["*.png", "*.jpg", "*.jpeg", "*.gif", "*.bmp", "*.tif", "*.tiff"]:
filters.append(f)
iList = QDir(fDir).entryInfoList(filters)
for f in iList:
im = self.image(f.filePath()).copy()
ico = QIcon(QPixmap.fromImage(im))
QListWidgetItem(ico, f.filePath(), self.ui.imgList)
if USE_COVERFLOW:
self.addCoverFlowItem(f)
if fDir:
self.lastDir = fDir
def resizeEvent(self, event):
if self.ui.tabWidget_2.currentIndex() == 1: #watermark tab
self.updateWatermarkPreview()
elif USE_COVERFLOW:
self.setCoverFlowSize()
def showEvent(self, event):
if USE_COVERFLOW:
self.setCoverFlowSize()
def setCoverFlowSize(self):
self.coverFlow.setSlideSize(QSize(self.coverFlow.height(), self.coverFlow.height()))
def dragEnterEvent(self, event):
event.acceptProposedAction()
def dropEvent(self, event):
for url in event.mimeData().urls():
fn = url.toLocalFile()
if fn.endsWith(".png", Qt.CaseInsensitive) or \
fn.endsWith(".jpg", Qt.CaseInsensitive) or \
fn.endsWith(".jpeg", Qt.CaseInsensitive) or \
fn.endsWith(".gif", Qt.CaseInsensitive) or \
fn.endsWith(".tiff", Qt.CaseInsensitive) or \
fn.endsWith(".tif", Qt.CaseInsensitive) or \
fn.endsWith(".bmp", Qt.CaseInsensitive):
im = self.image(fn).copy()
ico = QIcon(QPixmap.fromImage(im))
QListWidgetItem(ico, fn, self.ui.imgList)
if USE_COVERFLOW:
self.addCoverFlowItem(QFileInfo(fn))
def loadSettings(self):
if self.settings.contains("defaultsite"):
self.ui.comboSite.setCurrentIndex(self.ui.comboSite.findText(self.settings.value("defaultsite").toString()))
self.lastDir = self.settings.value("lastDir").toString()
self.ui.spinImg.setValue(self.settings.value("numImg", QVariant(4)).toInt()[0])
self.changeDisplayMode(self.settings.value("displayMode", QVariant(0)).toInt()[0])
self.settings.beginGroup("watermark")
self.watermark = self.settings.value("file").toString()
self.ui.spinOpacity.setValue(self.settings.value("opacity", QVariant(1)).toDouble()[0])
self.ui.watermarkX.setText(self.settings.value("x").toString())
self.ui.watermarkY.setText(self.settings.value("y").toString())
position = self.settings.value("position").toString()
if position == "bottomleft":
self.ui.rbBottomLeft.setChecked(True)
elif position == "bottomright":
self.ui.rbBottomRight.setChecked(True)
elif position == "upperright":
self.ui.rbUpperRight.setChecked(True)
elif position == "upperleft":
self.ui.rbUpperLeft.setChecked(True)
elif position == "tile":
self.ui.rbTiled.setChecked(True)
elif position == "scaled":
self.ui.rbScaled.setChecked(True)
elif position == "custom":
self.ui.rbCustom.setChecked(True)
self.wmCustomToggled(True)
self.settings.endGroup()
self.settings.beginGroup("format")
if self.settings.contains("defaultformat"):
self.ui.comboFormat.setCurrentIndex(self.ui.comboFormat.findText(self.settings.value("defaultformat").toString()))
if self.ui.comboFormat.currentText() == "JPEG":
self.ui.spinQuality.setEnabled(True)
self.ui.spinQuality.setValue(self.settings.value("quality", QVariant(75)).toInt()[0])
self.settings.endGroup()
def closeEvent(self, event):
self.settings.setValue("defaultsite", QVariant(self.ui.comboSite.currentText()))
self.settings.setValue("lastDir", QVariant(self.lastDir))
self.settings.setValue("numImg", QVariant(self.ui.spinImg.value()))
self.settings.setValue("displayMode", QVariant(self.displayIndex))
self.settings.beginGroup("watermark")
self.settings.setValue("file", QVariant(self.watermark))
self.settings.setValue("opacity", QVariant(self.ui.spinOpacity.value()))
self.settings.setValue("x", QVariant(self.ui.watermarkX.text()))
self.settings.setValue("y", QVariant(self.ui.watermarkY.text()))
if self.ui.rbBottomLeft.isChecked():
position="bottomleft"
elif self.ui.rbBottomRight.isChecked():
position="bottomright"
elif self.ui.rbUpperRight.isChecked():
position="upperright"
elif self.ui.rbUpperLeft.isChecked():
position="upperleft"
elif self.ui.rbTiled.isChecked():
position="tiled"
elif self.ui.rbScaled.isChecked():
position="scaled"
elif self.ui.rbCustom.isChecked():
position="custom"
self.settings.setValue("position", QVariant(position))
self.settings.endGroup()
self.settings.beginGroup("format")
self.settings.setValue("defaultformat", QVariant(self.ui.comboFormat.currentText()))
self.settings.setValue("quality", QVariant(self.ui.spinQuality.value()))
self.settings.endGroup()
for root, dirs, files in os.walk(tempfile.tempdir, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))
os.rmdir(tempfile.tempdir)
event.accept()
def cancelUpload(self):
self.uploadList = {}
self.site[str(self.ui.comboSite.currentText())].cancelUpload()
def scanSite(self):
self.site = {}
for s in dir(imgsite):
try:
if re.match("^[A-Z]", s):
c = eval("imgsite."+s+"(self)")
self.site[str(c)] = c
self.connect(c, SIGNAL("done(QString)"), self.upload)
except Exception, e:
QMessageBox.warning(None, "Exception", str(e))
for s in self.site:
self.ui.comboSite.addItem(s)
def addClicked(self):
ls = QFileDialog.getOpenFileNames(self, "Select images to upload",
self.lastDir,
"Images (*.png *.jpg *.jpeg *.gif *.bmp *.tif *.tiff);; All *.*")
for l in ls:
im = self.image(l).copy()
ico = QIcon(QPixmap.fromImage(im))
QListWidgetItem(ico, l, self.ui.imgList)
if USE_COVERFLOW:
self.addCoverFlowItem(QFileInfo(l))
self.lastDir = QFileInfo(l).absolutePath()
def removeClicked(self):
if display_modes[self.displayIndex] == "coverflow":
cfi = self.coverFlow.at(self.coverFlow.selected())
lIt = self.ui.imgList.findItems(cfi.title(), Qt.MatchExactly)
if len(lIt):
i = self.ui.imgList.takeItem(self.ui.imgList.row(lIt[0]))
del i
self.coverFlow.remove(cfi)
else:
item = self.ui.imgList.takeItem(self.ui.imgList.currentRow())
if USE_COVERFLOW:
for k in xrange(0, self.coverFlow.size()):
if self.coverFlow.at(k).title() == item.text():
del item
self.coverFlow.remove(k)
break
def uploadClicked(self):
self.uploadList = []
self.codeList = []
for i in xrange(0, self.ui.imgList.count()):
self.uploadList.append(self.ui.imgList.item(i).text())
self.ui.pbTotal.setMaximum(self.ui.imgList.count())
self.ui.pbTotal.setValue(0)
self.upload()
def upload(self, code=None):
if code:
self.codeList += [str(code)]
self.updateList()
self.ui.pbTotal.setValue(self.ui.pbTotal.value()+1)
if not len(self.uploadList):
QMessageBox.information(self, "Upload finished", "All images have been uploaded")
return
self.ui.lblTotal.setText("Uploading %d of %d"%(self.ui.pbTotal.value()+1, self.ui.pbTotal.maximum()))
it = self.uploadList.pop(0)
if self.watermark:
w = self.doWatermark(it)
it = os.path.join(tempfile.tempdir, str(QFileInfo(it).fileName()))
w.save(it)
if self.ui.comboFormat.currentIndex() != 0:
i = Image.open(str(it))
d = str(QFileInfo(it).baseName())+"."+str(self.ui.comboFormat.currentText()).lower()
it = os.path.join(tempfile.tempdir, d)
i.save(it, str(self.ui.comboFormat.currentText()), quality=self.ui.spinQuality.value())
self.site[str(self.ui.comboSite.currentText())].upload(it)
def updateList(self, value=None):
self.ui.textBBCode.clear()
i = 0
for code in self.codeList:
self.ui.textBBCode.setPlainText(self.ui.textBBCode.toPlainText()+code)
if i == self.ui.spinImg.value()-1:
self.ui.textBBCode.setPlainText(self.ui.textBBCode.toPlainText()+"\n")
i = 0
else:
i += 1
def addWatermark(self):
if not self.watermark:
last = self.lastDir
else:
last = QFileInfo(self.watermark).absolutePath()
f = QFileDialog.getOpenFileName(self, "Select watermark",
last,
"Images (*.png *.jpg *.jpeg *.gif *.bmp *.tif *.tiff);; All *.*")
self.watermark = f
self.updateWatermarkPreview()
def removeWatermark(self):
self.watermark = ""
self.ui.displayWatermark.setPixmap(QPixmap())
def doWatermark(self, it):
if self.ui.rbBottomLeft.isChecked():
position="bottomleft"
elif self.ui.rbBottomRight.isChecked():
position="bottomright"
elif self.ui.rbUpperRight.isChecked():
position="upperright"
elif self.ui.rbUpperLeft.isChecked():
position="upperleft"
elif self.ui.rbTiled.isChecked():
position="tiled"
elif self.ui.rbScaled.isChecked():
position="scaled"
elif self.ui.rbCustom.isChecked():
position=(self.ui.watermarkX.text(), self.ui.watermarkY.text())
w = watermark(it, self.watermark, position=position, opacity=self.ui.spinOpacity.value())
return w
def wmCustomToggled(self, checked):
if checked:
self.ui.watermarkX.setEnabled(True)
self.ui.watermarkY.setEnabled(True)
self.ui.labelX.setEnabled(True)
self.ui.labelY.setEnabled(True)
else:
self.ui.watermarkX.setEnabled(False)
self.ui.watermarkY.setEnabled(False)
self.ui.labelX.setEnabled(False)
self.ui.labelY.setEnabled(False)
def updateWatermarkPreview(self, *args, **kwargs):
if self.ui.imgList.count() == 0 and self.watermark:
self.ui.displayWatermark.setPixmap(QPixmap.fromImage(self.image(self.watermark)))
elif not self.watermark:
return
else:
w = ImageQt(self.doWatermark(self.ui.imgList.item(0).text()))
w = w.scaled(self.ui.displayWatermark.size())
self.ui.displayWatermark.setPixmap(QPixmap.fromImage(w))
def addCoverFlowItem(self, fileInfo):
if USE_COVERFLOW:
item = QLCoverFlowItem(self.image(fileInfo.absoluteFilePath()))#.scaledToWidth(200, Qt.SmoothTransformation))
item.setTitle(fileInfo.absoluteFilePath())
item.setComment(str(fileInfo.size()/1024)+"K")
self.coverFlow.add(item)
def image(self, path):
im = QImage()
try:
im = ImageQt(path)
except:
im = QImage(path)
return im
def formatChanged(self, value):
if self.ui.comboFormat.currentText() == "JPEG":
self.ui.spinQuality.setEnabled(True)
else:
self.ui.spinQuality.setEnabled(False)
if __name__ == '__main__':
app = QApplication(sys.argv)
sys.excepthook=handle_exception
mw = ImageUploader()
mw.show()
sys.exit(app.exec_())