def _thumbnail_movie_response(material, width, height, _watermark=False): filename = u'thumbnails/%(filename)s.%(width)sx%(height)s.jpg' % { 'filename': material.filename(), 'width': width, 'height': height, } WATERMARK_FILE = os.path.join(settings.MEDIA_ROOT, 'image/commons/movie.jpg') filename= os.path.join(settings.MEDIA_ROOT, filename) if not os.path.exists(filename): # ffmpegは日本語ファイル名を処理できないため一時ファイルを作成 import tempfile import commands source = os.path.join(settings.MEDIA_ROOT, material.file.name) ext = os.path.splitext(source)[1] f = open(source, 'rb') #tmp = tempfile.NamedTemporaryFile('wb', bufsize=f.size(), suffix=ext, delete=False) tmp = tempfile.NamedTemporaryFile(suffix=ext, delete=False) # tmp2は存在しているとエラーチェックに使えないのであえて`delete=False`を指定せずすぐに閉じている tmp2 = tempfile.NamedTemporaryFile() tmp2.close() tmp.write(f.read()) tmp.close() format = u'ffmpeg -ss %(sec)s -vframes 1 -i "%(movie)s" -s %(width)sx%(height)s -f image2 "%(output)s"' kwargs = { 'movie': tmp.name, 'width': width, 'height': height, 'output': tmp2.name, } FIRST_POS = 30 for i in xrange(0, FIRST_POS, 10): kwargs['sec'] = FIRST_POS - i commands.getstatusoutput(format % kwargs)[0] # ffmpegは正しいstatusを返さないようなのでファイルの存在で # 処理の実行ができたかを確認する if os.path.exists(tmp2.name): break if os.path.exists(tmp2.name): # 作成したサムネイルを移動 import shutil shutil.move(tmp2.name, filename) else: # 動画の切り取りに失敗したので画像ファイルを通常の画像ファイルを使用する filename = WATERMARK_FILE _watermark = False os.unlink(tmp.name) img = Image.open(filename) if img.size[0] > width or img.size[1] > height: img.thumbnail((width, height), Image.ANTIALIAS) if _watermark: mark = Image.open(WATERMARK_FILE) img = watermark.watermark(img, mark, 'tile', 0.1) response = HttpResponse(mimetype='image/jpeg') img.save(response, "jpeg") return response
def _watermark_image_response(material, width=None, height=None): WATERMARK = os.path.join(settings.MEDIA_ROOT, 'image/watermark.png') img = Image.open(material.file) if not width: width = img.size[0] if not height: height = img.size[1] if img.size[0] > width or img.size[1] > height: img.thumbnail((width, height), Image.ANTIALIAS) mark = Image.open(WATERMARK) img = watermark.watermark(img, mark, 'tile', 0.3) response = HttpResponse(mimetype='image/png') img.save(response, "PNG") return response