Guest User

Untitled

a guest
Dec 15th, 2018
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.19 KB | None | 0 0
  1. import os
  2. import sys
  3. import re
  4. from PIL import Image, ImageDraw, ImageFont
  5. from PyQt5.QtWidgets import *
  6. from PyQt5.QtCore import pyqtSignal
  7. from PyQt5.QtCore import QEvent
  8.  
  9. from datetime import datetime
  10. from os.path import getmtime
  11.  
  12. DEFAULT_ARTIST = "Taewoo Lee (anyzac.ltw@gmail.com)"
  13. DEFAULT_COPYRIGHT = "(C) AZ/GG/SKB/DW"
  14. DEFAULT_COMMENT = "No comment.\nAll copyrights are auto-generated."
  15. DEFAULT_FONT = './arial.ttf'
  16. TITLE_FONT_SIZE = 0.02
  17. COPYRIGHT_FONT_SIZE = 0.01
  18. COMMENT_FONT_SIZE = 0.01
  19. MARGIN_RATE = 0.05 # ex) height * 0.05
  20.  
  21. # 파일명에 이미 날짜가 들어가 있는 경우의 처리
  22. def filename_has_date(filePath):
  23. '파일명 앞에 yyymmdd 형태의 날짜가 적혀져 있으면 True를 리턴한다'
  24. yyyymmdd_re = re.compile('[0-9]{8}_.*')
  25. filename = os.path.splitext(os.path.basename(filePath))[0]
  26. if yyyymmdd_re.match(filename):
  27. return True
  28. else:
  29. return False
  30.  
  31. def stamp(filePath, artist, comment, copyright, logger):
  32. try:
  33. img = Image.open(filePath)
  34. except:
  35. logger.log('%s 는 이미지 파일이 아닙니다.' % filePath)
  36. return
  37.  
  38. # 배경색을 얻는다.
  39. bg_color = img.getpixel( (0,0) )
  40. fg_color = (255-bg_color[0], 255-bg_color[1], 255-bg_color[2], 255)
  41.  
  42. _orgn_bbox = img.getbbox()
  43. _orgn_width = _orgn_bbox[2]
  44. _orgn_height = _orgn_bbox[3]
  45.  
  46. # 여백 계산
  47. margin_v = round(_orgn_height * MARGIN_RATE)
  48. margin = {
  49. 'top': margin_v,
  50. 'left': 0,
  51. 'right': 0,
  52. 'bottom': round(margin_v * 0.5)
  53. }
  54.  
  55. # 여백을 포함하여 Crop 하기
  56. crop_bbox = (
  57. _orgn_bbox[0] - margin['left'],
  58. _orgn_bbox[1] - margin['top'],
  59. _orgn_bbox[2] + margin['right'],
  60. _orgn_bbox[3] + margin['bottom']
  61. )
  62. img = img.crop(crop_bbox)
  63.  
  64. # Crop 이후
  65. bbox = img.getbbox()
  66. # fix bbox !!
  67. bbox = (bbox[0], bbox[1]-margin['top'], bbox[2], bbox[3]+margin['bottom'])
  68. top_area = ( 0, 0, bbox[2], margin['top'] )
  69. bottom_area = ( 0, bbox[3] - margin['bottom'], bbox[2], bbox[3] )
  70.  
  71. draw = ImageDraw.Draw(img)
  72. draw.rectangle(top_area, outline=None, fill=bg_color)
  73. draw.rectangle(bottom_area, outline=None, fill=bg_color)
  74.  
  75. # 폰트 사이즈 결정
  76. title_fnt_size = round(min(_orgn_width, _orgn_height) * TITLE_FONT_SIZE)
  77. title_fnt = ImageFont.truetype(DEFAULT_FONT, title_fnt_size)
  78.  
  79. copyright_fnt_size = round(min(_orgn_width, _orgn_height) * COPYRIGHT_FONT_SIZE)
  80. copyright_fnt = ImageFont.truetype(DEFAULT_FONT, copyright_fnt_size)
  81.  
  82. comment_fnt_size = round(min(_orgn_width, _orgn_height) * COMMENT_FONT_SIZE)
  83. comment_fnt = ImageFont.truetype(DEFAULT_FONT, comment_fnt_size)
  84.  
  85. # 타이틀 그리기
  86. title_text = ''
  87. if filename_has_date(filePath):
  88. title_text = '[%s]' % os.path.splitext(os.path.basename(filePath))[0]
  89. else:
  90. yyyymmdd = datetime.fromtimestamp(getmtime(filePath)).strftime('%Y%m%d')
  91. filename = os.path.splitext( os.path.basename(filePath) )[0]
  92. title_text = '[%s_%s]' % (yyyymmdd, filename)
  93. draw.text((50,50), title_text, font=title_fnt, fill=fg_color )
  94.  
  95. # 카피 라이트 그리기
  96. copyright_text = copyright
  97. copyright_w, copyright_h = draw.textsize(copyright_text, copyright_fnt)
  98. copyright_x = round(_orgn_width/2 - copyright_w/2)
  99. copyright_y = bbox[3] - margin['bottom'] + round(copyright_h/2)
  100. draw.text( (copyright_x, copyright_y), copyright_text, font=copyright_fnt, fill=fg_color )
  101.  
  102. # 추가 정보 그리기
  103. add_text = 'Artist: %s\nComment:\n%s' % (artist, comment)
  104. add_text_w, add_text_h = draw.textsize(add_text, comment_fnt)
  105. add_text_x = bbox[2] - add_text_w - 50
  106. add_text_y = bbox[0] + 50
  107. draw.text( (add_text_x, add_text_y), add_text, font=comment_fnt, fill=fg_color )
  108.  
  109. # 저장하기
  110. pre, ext = os.path.splitext(filePath)
  111. output = pre + '_Sealed.png'
  112. try:
  113. img.save(output)
  114. except:
  115. logger.log('%s 저장에 실패했습니다.' % filePath)
  116. return
  117. logger.log('%s 성공.' % filePath)
  118.  
  119. class FileListView(QListWidget):
  120. def __init__(self, parent):
  121. super().__init__(parent)
  122. self.setAcceptDrops(True)
  123.  
  124. def dragEnterEvent(self, event):
  125. if event.mimeData().hasUrls():
  126. event.accept()
  127. else:
  128. event.ignore()
  129.  
  130. def dragMoveEvent(self, event):
  131. event.accept()
  132.  
  133. def dropEvent(self, event):
  134. if event.mimeData().hasUrls():
  135. event.accept()
  136. for url in event.mimeData().urls():
  137. filePath = str(url.toLocalFile())
  138. self.addItem(filePath)
  139. else:
  140. event.ignore()
  141.  
  142. def removeSelected(self):
  143. for item in self.selectedItems():
  144. n = self.row(item)
  145. self.takeItem(n)
  146.  
  147. def getFileList(self):
  148. result = []
  149. max = self.count()
  150. for i in range(max):
  151. item = self.item(i)
  152. result.append(item.text())
  153. return result
  154.  
  155. class CopyrighterWindow(QWidget):
  156. def __init__(self):
  157. super().__init__()
  158. self.setWindowTitle("Copyrighter")
  159. self.setGeometry(300, 300, 900, 450)
  160.  
  161. self.hLayout = QHBoxLayout()
  162. self.setLayout(self.hLayout)
  163.  
  164. # Left VLayout
  165. self.vLayout = QVBoxLayout()
  166. self.hLayout.addLayout(self.vLayout)
  167.  
  168. # Right VLayout
  169. self.vLayoutR = QVBoxLayout()
  170. self.hLayout.addLayout(self.vLayoutR)
  171. self.logForm = QPlainTextEdit('', self)
  172. self.vLayoutR.addWidget(self.logForm)
  173.  
  174. # Files list
  175. self.fileListView = FileListView(self)
  176. self.vLayout.addWidget(self.fileListView)
  177.  
  178. # Remove File Button
  179. self.removeFileButton = QPushButton("Remove", self)
  180. self.removeFileButton.clicked.connect(self.fileListView.removeSelected)
  181. self.vLayout.addWidget(self.removeFileButton)
  182.  
  183. # Grid Layout
  184. self.gridLayout = QGridLayout()
  185. self.vLayout.addLayout(self.gridLayout)
  186.  
  187. # Title Form
  188. self.titleCheckbox = QCheckBox("Title", self)
  189. self.titleCheckbox.setChecked(True)
  190. # self.titleForm = QLineEdit("", self)
  191. self.gridLayout.addWidget(self.titleCheckbox,0,0)
  192. # self.gridLayout.addWidget(self.titleForm,0,1)
  193.  
  194. # Artist Form
  195. self.artistCheckbox = QCheckBox("Artist", self)
  196. self.artistCheckbox.setChecked(True)
  197. self.artistForm = QLineEdit(DEFAULT_ARTIST)
  198. self.gridLayout.addWidget(self.artistCheckbox,1,0)
  199. self.gridLayout.addWidget(self.artistForm,1,1)
  200.  
  201. # Copyright Form
  202. self.copyrightCheckbox = QCheckBox("Copyright", self)
  203. self.copyrightCheckbox.setChecked(True)
  204. self.copyrightForm = QLineEdit(DEFAULT_COPYRIGHT, self)
  205. self.gridLayout.addWidget(self.copyrightCheckbox,2,0)
  206. self.gridLayout.addWidget(self.copyrightForm,2,1)
  207.  
  208. # Comment Form
  209. self.commentCheckbox = QCheckBox("Comment", self)
  210. self.commentCheckbox.setChecked(True)
  211. # self.commentForm = QLineEdit(DEFAULT_COMMENT, self)
  212. self.commentForm = QPlainTextEdit(DEFAULT_COMMENT, self)
  213. self.gridLayout.addWidget(self.commentCheckbox,3,0)
  214. self.gridLayout.addWidget(self.commentForm,3,1)
  215.  
  216. # Start Button
  217. self.startButton = QPushButton("Start", self)
  218. self.startButton.clicked.connect(self.startButtonClicked)
  219. self.vLayout.addWidget(self.startButton)
  220.  
  221. def drawTitleCheckboxChanged(self):
  222. if self.drawTitleCheckbox.isChecked() == True:
  223. QMessageBox.about(self, "Info", "Checked")
  224.  
  225. def startButtonClicked(self):
  226. self.run()
  227.  
  228. def log(self, text):
  229. self.logForm.insertPlainText(text + '\n')
  230.  
  231. def run(self):
  232. # self.title = filename
  233. artist = self.artistForm.text()
  234. comment = self.commentForm.toPlainText()
  235. copyright = self.copyrightForm.text()
  236. files = self.fileListView.getFileList()
  237. for file in files:
  238. stamp(file, artist, comment, copyright, self)
  239.  
  240. if __name__ == "__main__":
  241. app = QApplication(sys.argv)
  242. win = CopyrighterWindow()
  243. win.show()
  244. app.exec_()
Add Comment
Please, Sign In to add comment