def create_thumbnail(filename, thumbnail=None): """ cache image for faster access """ thumb = vfs.getoverlay(filename + '.raw') image = None if thumbnail: try: image = imlib2.open_from_memory(thumbnail) except Exception, e: print 'Invalid thumbnail for %s' % filename if config.DEBUG: print 'invalid thumbnail:', e
def prepare_subsample(src_file, dst_dir, dst_file, sizes, force=False): """ Scale an image, fixing orientation Metadata will be removed, if size is 'hi' the following info will be preserved: * Date taken """ if sizes.__class__ in [str, unicode]: assert sizes in config.SUBSAMPLES_GEOM.keys() sizes = [sizes] size_info = {} for s in sizes: formatted_dst_file = dst_file.format(size=s) size_info[s] = { 'todo': force, 'dst_path': join(dst_dir, formatted_dst_file), 'dst_file': formatted_dst_file } if not isfile(size_info[s]['dst_path']): size_info[s]['todo'] = True elif getmtime(size_info[s]['dst_path']) < getmtime(src_file): size_info[s]['todo'] = True else: continue if not isdir(dst_dir): makedirs(dst_dir) for s in sizes: if not size_info[s]['todo']: size_info.pop(s) if len(size_info) > 0: with file(src_file) as buf: img = il2.open_from_memory(buf.read()) if GEXIV_SUPPORT: (slim_meta, orientation) = extract_base_meta(src_file) fix_img_orientation(img, orientation) for s in size_info: if len(size_info) > 1: img_new = img.copy() else: img_new = img img_new.thumbnail(config.SUBSAMPLES_GEOM[s]) img_new.save(join(dst_dir, size_info[s]['dst_file'])) if GEXIV_SUPPORT and slim_meta != None and s == 'hi': slim_meta.save_file(size_info[s]['dst_path'])
def get_image(filename, scale, size): cache_key = '%s-%s-%dx%d' % (filename, scale, size[0], size[1]) # First check the loaded image cache image = image_cache[cache_key] # Second check the on disk cache if config.CACHE_IMAGES and not image: if vfs.isoverlay(filename): cache_dir = os.path.dirname(filename) else: cache_dir = vfs.getoverlay(filename) root,ext = os.path.splitext(filename) cache_file = '%s-%s-%dx%d%s' % (USABLE_RESOLUTION, scale, size[0], size[1], ext) cache_filename = os.path.join(cache_dir, cache_file) if vfs.exists(cache_filename) and vfs.mtime(cache_filename) > vfs.mtime(filename): image = imlib2.open(cache_filename) image_cache[cache_key] = image # Finally load the image and scale it as required. if not image: if filename.startswith('http://') or filename.startswith('https://'): fp = webcache.get_default_cache().get(filename) image = imlib2.open_from_memory(fp.read()) fp.close() else: image = imlib2.open(filename) w = image.width h = image.height src_size = (image.width, image.height) if scale == 'horizontal': w = size[0] dst_size = (w, h) elif scale == 'vertical': h = size[1] dst_size = (w, h) elif scale == 'both': w = size[0] h = size[1] dst_size = (w, h) elif scale == 'aspect': aspect_ratio = float(w) / float(h) w = size[0] h = int(float(w) / aspect_ratio) if h > size[1]: w = int(float(size[1]) * aspect_ratio) h = size[1] dst_size = (w, h) else: if w > size[0]: w = size[0] if h > size[1]: h = size[1] size = (w, h) src_size = size dst_size = size logger.log( 9, 'Creating image %s (%dx%d) of size %dx%d using scale %s', filename, src_size[0], src_size[1], dst_size[0], dst_size[1], scale) image = image.scale(dst_size, src_size=src_size) image_cache[cache_key] = image if config.CACHE_IMAGES: if not vfs.exists(cache_dir): os.makedirs(cache_dir) image.save(cache_filename) logger.debug('Saved to %s', cache_filename) return image
def makeThumb(): #データベースに取得(ファイル) con = sqlite3.connect(u"data.db") c = con.execute(u"select * from Picture") pictureList = c.fetchall() #データファイルツリー作成 for fileInfo in pictureList: #親ディレクトリの作成 upperDir_link = os.path.dirname(fileInfo[1]) if not os.path.isdir(upperDir_link): os.makedirs(upperDir_link) upperDir_L = os.path.dirname(fileInfo[2]) if not os.path.isdir(upperDir_L): os.makedirs(upperDir_L) upperDir_S = os.path.dirname(fileInfo[3]) if not os.path.isdir(upperDir_S): os.makedirs(upperDir_S) #更新があった場合 updateTime= os.path.getmtime(fileInfo[0]) if updateTime > fileInfo[5]: #リンクの作成 if not os.path.isfile(fileInfo[1].encode("utf-8")): os.symlink(os.path.abspath(fileInfo[0]).encode("utf-8"),fileInfo[1].encode("utf-8")) #NEF (raw data) サポート.とりあえずリンクだけ作っとく if not os.path.isfile(fileInfo[1].encode("utf-8").split(".JPG")[0] + ".NEF"): if os.path.isfile(os.path.abspath(fileInfo[0]).encode("utf-8").split(".JPG")[0] + ".NEF"): os.symlink(os.path.abspath(fileInfo[0]).encode("utf-8").split(".JPG")[0] + ".NEF",fileInfo[1].encode("utf-8").split(".JPG")[0] + ".NEF") #サムネイルの作成 if (not os.path.isfile(fileInfo[2].encode("utf-8"))) or (not os.path.isfile(fileInfo[2].encode("utf-8"))) : print fileInfo[0] data = file(fileInfo[0]).read() imgL = imlib2.open_from_memory(data) imgS = imlib2.open_from_memory(data) newImgL = imgL.scale_preserve_aspect((800,800)) imgS.thumbnail((150,150)) try: exif = EXIF.process_file(open(fileInfo[1]),details=False,stop_tag=u"Image Orientation") if unicode(exif["Image Orientation"]).find(u"Rotated 90 CW") != -1: imgS.orientate(3) newImgL.orientate(3) elif unicode(exif["Image Orientation"]).find(u"Rotated 90 CCW") != -1: imgS.orientate(1) newImgL.orientate(1) elif unicode(exif["Image Orientation"]).find(u"Rotated 180") != -1: imgS.orientate(2) newImgL.orientate(2) except: print "exif key error. Key \"Image Orientation\" not found. Exif information may not exist." newImgL.save(fileInfo[2].encode("utf-8"),"jpeg") imgS.save(fileInfo[3].encode("utf-8"),"jpeg") print "更新:", fileInfo[0] #更新時間データを更新 con.execute(u"update Picture set last_update=? where path_orig=?",(updateTime,fileInfo[0]) ) #データベース終了処理 con.commit() con.close()
# Grrr I wish Amazon wouldn't return an empty gif (807b) for i in range(len(cover)): m = None imageFound = False try: if cover[i].ImageUrlLarge: m = urllib2.urlopen(cover[i].ImageUrlLarge) imageFound = True except urllib2.URLError, e: print 'URLError: %s' % (e) except urllib2.HTTPError, e: # Amazon returned a 404 print 'HTTPError: %s' % (e) if imageFound and (m.info()['Content-Length'] != '807'): image = Image.open_from_memory(m.read()) items += [ menu.MenuItem('%s' % cover[i].ProductName, self.cover_create, cover[i].ImageUrlLarge, image=image) ] else: # see if a small one is available try: if cover[i].ImageUrlMedium: if m: m.close() m = urllib2.urlopen(cover[i].ImageUrlMedium) imageFound = True except urllib2.HTTPError: pass
# Check if the logos directory exists, if not, make it before # proceeding if not os.path.isdir(config.TV_LOGOS): print "Logo directory does not exist\n" print "Creating: %s\n" % (config.TV_LOGOS) os.mkdir(config.TV_LOGOS) x = xmltv.read_channels(open(config.XMLTV_FILE)) for i in x: try: imgsrc = i['icon'][0]['src'] except KeyError: imgsrc = None channel = i['id'] #print '%s - %s' % (imgsrc, channel) if imgsrc: try: img = imlib2.open_from_memory(urllib2.urlopen(str(imgsrc)).read()) # Convert the image into a PNG and save to logos directory output_file = config.TV_LOGOS + '/' + channel + '.png' try: img.save(output_file) print 'Saved "%s" for channel "%s"' % (output_file, channel) except IOError, e: print e except Exception, e: print 'Failed to get "%s" for channel "%s"\nerror "%s"' % (imgsrc, channel, e)
def get_image(filename, scale, size): cache_key = '%s-%s-%dx%d' % (filename, scale, size[0], size[1]) # First check the loaded image cache image = image_cache[cache_key] # Second check the on disk cache if config.CACHE_IMAGES and not image: if vfs.isoverlay(filename): cache_dir = os.path.dirname(filename) else: cache_dir = vfs.getoverlay(filename) root, ext = os.path.splitext(filename) cache_file = '%s-%s-%dx%d%s' % (USABLE_RESOLUTION, scale, size[0], size[1], ext) cache_filename = os.path.join(cache_dir, cache_file) if vfs.exists(cache_filename ) and vfs.mtime(cache_filename) > vfs.mtime(filename): image = imlib2.open(cache_filename) image_cache[cache_key] = image # Finally load the image and scale it as required. if not image: if filename.startswith('http://') or filename.startswith('https://'): fp = webcache.get_default_cache().get(filename) image = imlib2.open_from_memory(fp.read()) fp.close() else: image = imlib2.open(filename) w = image.width h = image.height src_size = (image.width, image.height) if scale == 'horizontal': w = size[0] dst_size = (w, h) elif scale == 'vertical': h = size[1] dst_size = (w, h) elif scale == 'both': w = size[0] h = size[1] dst_size = (w, h) elif scale == 'aspect': aspect_ratio = float(w) / float(h) w = size[0] h = int(float(w) / aspect_ratio) if h > size[1]: w = int(float(size[1]) * aspect_ratio) h = size[1] dst_size = (w, h) else: if w > size[0]: w = size[0] if h > size[1]: h = size[1] size = (w, h) src_size = size dst_size = size logger.log(9, 'Creating image %s (%dx%d) of size %dx%d using scale %s', filename, src_size[0], src_size[1], dst_size[0], dst_size[1], scale) image = image.scale(dst_size, src_size=src_size) image_cache[cache_key] = image if config.CACHE_IMAGES: if not vfs.exists(cache_dir): os.makedirs(cache_dir) image.save(cache_filename) logger.debug('Saved to %s', cache_filename) return image
try: image = imlib2.open_from_memory(thumbnail) except Exception, e: print 'Invalid thumbnail for %s' % filename if config.DEBUG: print 'invalid thumbnail:', e if not image: if __freevo_app__ == 'main': try: f = open(filename, 'rb') tags = exif.process_file(f) f.close() if tags.has_key('JPEGThumbnail'): image = imlib2.open_from_memory(tags['JPEGThumbnail']) except Exception, e: print 'Error loading thumbnail %s' % filename if config.DEBUG: print 'create_thumbnail:', e if not image or image.width < 100 or image.height < 100: try: image = imlib2.open(filename) except Exception, e: print 'error caching image %s' % filename if config.DEBUG: print 'caching image:', e return None try:
url = item.MediumImage.URL width = item.LargeImage.Width height = item.LargeImage.Height if url is not None: imageFound = False m = None try: m = urllib2.urlopen(item.LargeImage.URL) imageFound = True except urllib2.URLError, e: logger.info('URLError: %s', e) except urllib2.HTTPError, e: # Amazon returned a 404 logger.info('HTTPError: %s', e) if imageFound and (m.info()['Content-Length'] != '807'): image = imlib2.open_from_memory(m.read()) items += [ menu.MenuItem('%s (%sx%s)' % (title, width, height), self.cover_create, url, image=image) ] else: # maybe the url is wrong, try to change '.01.' to '.03.' url = url.replace('.01.', '.03.') try: m = urllib2.urlopen(item.LargeImage.URL) imageFound = True except urllib2.URLError, e: logger.info('URLError: %s', e) except urllib2.HTTPError, e: # Amazon returned a 404 logger.info('HTTPError: %s', e) if imageFound and (m.info()['Content-Length'] != '807'): image = imlib2.open_from_memory(m.read())
# Check if the logos directory exists, if not, make it before # proceeding if not os.path.isdir(config.TV_LOGOS): print "Logo directory does not exist\n" print "Creating: %s\n" % (config.TV_LOGOS) os.mkdir(config.TV_LOGOS) x = xmltv.read_channels(open(config.XMLTV_FILE)) for i in x: try: imgsrc = i['icon'][0]['src'] except KeyError: imgsrc = None channel = i['id'] #print '%s - %s' % (imgsrc, channel) if imgsrc: try: img = imlib2.open_from_memory(urllib2.urlopen(str(imgsrc)).read()) # Convert the image into a PNG and save to logos directory output_file = config.TV_LOGOS + '/' + channel + '.png' try: img.save(output_file) print 'Saved "%s" for channel "%s"' % (output_file, channel) except IOError, e: print e except Exception, e: print 'Failed to get "%s" for channel "%s"\nerror "%s"' % ( imgsrc, channel, e)
def cover_search_file(self, arg=None, menuw=None): """ search imdb for this item """ box = PopupBox(text=_('searching Amazon...')) box.show() album = self.item.getattr('album') if not album: album = self.item.getattr('title') artist = self.item.getattr('artist') # Maybe the search string need encoding to config.LOCALE search_string = '%s %s' % (artist.encode(query_encoding), album.encode(query_encoding)) search_string = re.sub('[\(\[].*[\)\]]', '', search_string) if config.DEBUG > 1: print "search_string=%r" % search_string try: cover = amazon.searchByKeyword(search_string, product_line="music") except amazon.AmazonError: box.destroy() dict_tmp = {'artist': artist, 'album': album} box = PopupBox(text=_('No matches for %(artist)s - %(album)s') % dict_tmp) box.show() time.sleep(2) box.destroy() return except: box.destroy() box = PopupBox(text=_('Unknown error while searching.')) box.show() time.sleep(2) box.destroy() return items = [] # Check if they're valid before presenting the list to the user # Grrr I wish Amazon wouldn't return an empty gif (807b) MissingFile = False m = None n = None for i in range(len(cover)): try: m = urllib2.urlopen(cover[i].ImageUrlLarge) except urllib2.HTTPError: # Amazon returned a 404 MissingFile = True if not MissingFile and not (m.info()['Content-Length'] == '807'): image = Image.open_from_memory(m.read()) items += [ menu.MenuItem('%s' % cover[i].ProductName, self.cover_create, cover[i].ImageUrlLarge, image=image) ] m.close() else: if m: m.close() MissingFile = False # see if a small one is available try: n = urllib2.urlopen(cover[i].ImageUrlMedium) except urllib2.HTTPError: MissingFile = True if not MissingFile and not (n.info()['Content-Length'] == '807'): image = Image.open_from_memory(n.read()) items += [ menu.MenuItem( ('%s [' + _('small') + ']') % cover[i].ProductName, self.cover_create, cover[i].ImageUrlMedium) ] n.close() else: if n: n.close() # maybe the url is wrong, try to change '.01.' to '.03.' cover[i].ImageUrlLarge = cover[i].ImageUrlLarge.replace( '.01.', '.03.') try: n = urllib2.urlopen(cover[i].ImageUrlLarge) if not (n.info()['Content-Length'] == '807'): image = Image.open_from_memory(n.read()) items += [ menu.MenuItem(('%s [' + _('small') + ']') % cover[i].ProductName, self.cover_create, cover[i].ImageUrlLarge) ] n.close() except urllib2.HTTPError: pass box.destroy() if len(items) == 1: self.cover_create(arg=items[0].arg, menuw=menuw) return if items: moviemenu = menu.Menu(_('Cover Search Results'), items) menuw.pushmenu(moviemenu) return box = PopupBox(text=_('No covers available from Amazon')) box.show() time.sleep(2) box.destroy() return
width = item.LargeImage.Width height = item.LargeImage.Height if url is not None: imageFound = False m = None try: m = urllib2.urlopen(item.LargeImage.URL) imageFound = True except urllib2.URLError, e: logger.info('URLError: %s', e) except urllib2.HTTPError, e: # Amazon returned a 404 logger.info('HTTPError: %s', e) if imageFound and (m.info()['Content-Length'] != '807'): image = imlib2.open_from_memory(m.read()) items += [ menu.MenuItem('%s (%sx%s)' % (title, width, height), self.cover_create, url, image=image) ] else: # maybe the url is wrong, try to change '.01.' to '.03.' url = url.replace('.01.', '.03.') try: m = urllib2.urlopen(item.LargeImage.URL) imageFound = True except urllib2.URLError, e: logger.info('URLError: %s', e)