def cover_create(self, arg=None, menuw=None): """ create cover file for the item """ import directory box = PopupBox(text= _('getting data...')) box.show() #filename = os.path.splitext(self.item.filename)[0] if self.item.type == 'audiocd': filename = '%s/disc/metadata/%s.jpg' % (config.OVERLAY_DIR, self.item.info['id']) elif self.item.type == 'dir': filename = os.path.join(self.item.dir, 'cover.jpg') else: filename = '%s/cover.jpg' % (os.path.dirname(self.item.filename)) fp = urllib2.urlopen(str(arg)) m = vfs.open(filename,'wb') m.write(fp.read()) m.close() fp.close() # try to crop the image to avoid ugly borders try: image = imlib2.open(filename) width, height = image.size image.crop((2, 2), (width-4, height-4)).save(filename) util.cache_image(filename) except Exception, why: logger.warning(why)
def cover_create(self, arg=None, menuw=None): """ create cover file for the item """ import directory box = PopupBox(text=_('getting data...')) box.show() #filename = os.path.splitext(self.item.filename)[0] if self.item.type == 'audiocd': filename = '%s/disc/metadata/%s.jpg' % (config.OVERLAY_DIR, self.item.info['id']) elif self.item.type == 'dir': filename = os.path.join(self.item.dir, 'cover.jpg') else: filename = '%s/cover.jpg' % (os.path.dirname(self.item.filename)) fp = urllib2.urlopen(str(arg)) m = vfs.open(filename, 'wb') m.write(fp.read()) m.close() fp.close() # try to crop the image to avoid ugly borders try: image = imlib2.open(filename) width, height = image.size image.crop((2, 2), (width - 4, height - 4)).save(filename) util.cache_image(filename) except Exception, why: logger.warning(why)
def fetch_image(self): """Fetch the best image""" if config.DEBUG: print 'fetch_image', self.image_urls image_len = 0 if len(self.image_urls) == 0: # No images return for image in self.image_urls: try: print 'image:', image # get sizes of images req = urllib2.Request(image, txdata, txheaders) r = urllib2.urlopen(req) length = int(r.info()['Content-Length']) r.close() if length > image_len: image_len = length self.image_url = image except: pass if not self.image_url: print "Image dowloading failed" return self.image = (self.fxdfile + '.jpg') req = urllib2.Request(self.image_url, txdata, txheaders) r = urllib2.urlopen(req) i = vfs.open(self.image, 'w') i.write(r.read()) i.close() r.close() # try to crop the image to avoid borders by imdb try: import kaa.imlib2 as Image image = Image.open(filename) width, height = image.size image.crop((2,2,width-4, height-4)).save(filename) except: pass self.image = vfs.basename(self.image) print "Downloaded cover image from %s" % self.image_url print "Freevo knows nothing about the copyright of this image, please" print "go to %s to check for more informations about private." % self.image_url print "use of this image"
def fetch_image(self): """Fetch the best image""" logger.debug('fetch_image=%s', self.image_urls) image_len = 0 if len(self.image_urls) == 0: # No images return for image in self.image_urls: try: logger.debug('image=%s', image) # get sizes of images req = urllib2.Request(image, txdata, txheaders) r = urllib2.urlopen(req) length = int(r.info()['Content-Length']) r.close() if length > image_len: image_len = length self.image_url = image except: pass if not self.image_url: print "Image downloading failed" return self.image = (self.fxdfile + '.jpg') req = urllib2.Request(self.image_url, txdata, txheaders) r = urllib2.urlopen(req) i = vfs.open(self.image, 'w') i.write(r.read()) i.close() r.close() # try to crop the image to avoid borders by imdb try: import kaa.imlib2 as Image image = Image.open(filename) width, height = image.size image.crop((2,2,width-4, height-4)).save(filename) except: pass self.image = vfs.basename(self.image) logger.debug('Downloaded cover image from %s', self.image_url) print "Freevo knows nothing about the copyright of this image, please go to" print "%s to check for more information about private use of this image." % self.image_url
def process(self): # TODO fix font locations to be configurable imlib2.add_font_path("/usr/share/fonts/truetype/") imlib2.add_font_path("/usr/share/fonts/truetype/freefont/") self.default_font = imlib2.load_font("FreeSans", 20) wf = self.artifact.previous_artifact_filepath image = imlib2.open(wf) new_image = self.do_im(image) # Most of the time, we can just modify the image in do_im, but in some # cases we need to return a new image object, i.e. when cropping. So, # if do_im returns anything replace the image with the returned image. if new_image: image = new_image image.save(self.artifact.filepath())
def create_www_thumbnail(filename): '''creates a webserver thumbnail image and returns its size. ''' thumb_path = www_thumbnail_path(filename) try: try: if not os.path.isdir(os.path.dirname(thumb_path)): os.makedirs(os.path.dirname(thumb_path), mode=04775) except IOError: print 'error creating dir %s' % os.path.dirname(thumb_path) raise IOError image = imlib2.open(filename) thumb = image.scale_preserve_aspect(config.WWW_IMAGE_THUMBNAIL_SIZE) thumb.save(thumb_path) except IOError, e: print e return (0, 0)
def process(self): font_paths = self.FONT_PATHS if self.artifact.args.has_key('font-path'): font_paths.extend(self.artifact.args['font-path']) for path in font_paths: imlib2.add_font_path(path) self.default_font = imlib2.load_font("FreeSans", 20) wf = self.artifact.previous_artifact_filepath image = imlib2.open(wf) new_image = self.do_im(image) # Most of the time, we can just modify the image in do_im, but in some # cases we need to return a new image object, i.e. when cropping. So, # if do_im returns anything replace the image with the returned image. if new_image: image = new_image image.save(self.artifact.filepath())
def as_image(self): if not imlib2: assert CanvasError, "kaa.imlib2 not available." if not self["image"]: # No existing Imlib2 image, so we need to make one. if (self["filename"] and self._loaded) or (not self["filename"] and self._o): # The evas object already exists, so create a new Imlib2 image # from the evas data and tell evas to use that buffer for the # image instead. size = self._o.size_get() self["image"] = imlib2.new(size, self._o.data_get(), copy = True) self._o.data_set(self["image"].get_raw_data(), copy = False) elif self["filename"]: # Evas object not created yet, self["image"] = imlib2.open(self["filename"]) elif self["pixels"]: raise CanvasError, "Can't convert not-yet-imported pixels to image." self["image"].signals["changed"].connect_weak(self.set_dirty) return self["image"]
def cover_create(self, arg=None, menuw=None): """ create cover file for the item """ import directory box = PopupBox(text=_('getting data...')) box.show() #filename = os.path.splitext(self.item.filename)[0] if self.item.type == 'audiocd': filename = '%s/disc/metadata/%s.jpg' % (config.OVERLAY_DIR, self.item.info['id']) elif self.item.type == 'dir': filename = os.path.join(self.item.dir, 'cover.jpg') else: filename = '%s/cover.jpg' % (os.path.dirname(self.item.filename)) fp = urllib2.urlopen(str(arg)) m = vfs.open(filename, 'wb') m.write(fp.read()) m.close() fp.close() # try to crop the image to avoid ugly borders try: image = Image.open(filename) width, height = image.size image.crop((2, 2, width - 4, height - 4)).save(filename) except: pass if self.item.type in ('audiocd', 'dir'): self.item.image = filename elif self.item.parent.type == 'dir': # set the new cover to all items self.item.parent.image = filename for i in self.item.parent.menu.choices: i.image = filename # check if we have to go one menu back (called directly) or # two (called from the item menu) back = 1 if menuw.menustack[-2].selected != self.item: back = 2 # maybe we called the function directly because there was only one # cover and we called it with an event if menuw.menustack[-1].selected == self.item: back = 0 # update the directory if directory.dirwatcher: directory.dirwatcher.scan() # go back in menustack for i in range(back): menuw.delete_menu() if back == 0: menuw.refresh() box.destroy()
@returns: tuple of positions and width """ if image_w >= text_w: image_x = 0 text_x = ((image_w - text_w) / 2) else: image_x = ((text_w - image_w) / 2) text_x = 0 image_y = osd.y + 7 text_y = osd.y + 55 - text_h width = image_w > text_w and image_w or text_w return (image_x, image_y, text_x, text_y, width) def draw(self, (type, object), x, osd): """ Draw the icon and temperature on the idlebar @returns: width of the icon """ logger.log( 9, 'draw((type=%r, object=%r), x=%r, osd=%r)', type, object, x, osd) temp, icon = self.checkweather() image_file = os.path.join(config.ICON_DIR, 'weather', icon) w, h = imlib2.open(image_file).size temperature = u'%s\xb0' % temp font = osd.get_font(config.OSD_IDLEBAR_FONT) widthtxt = font.stringsize(temperature) (image_x, image_y, text_x, text_y, width) = self.calc_positions(osd, w, h, widthtxt, font.h) osd.draw_image(image_file, (x+image_x, image_y, -1, -1)) osd.write_text(temperature, font, None, x+text_x, text_y, widthtxt, font.h, 'center', 'top') return width
def scape_image(filename, width): image = imlib2.open(filename) image = image.scale((width, -1)) image.save(filename)
def snapshot(videofile, imagefile=None, pos=None, update=True, popup=None): """ make a snapshot of the videofile at position pos to imagefile """ from subprocess import Popen, PIPE import kaa.imlib2 as Image import vfs import gui.PopupBox import osd # skip broken symlinks if os.path.islink(videofile) and not os.path.exists(videofile): return if not imagefile: imagefile = vfs.getoverlay(videofile + '.raw') if not update and os.path.isfile(imagefile) and \ os.stat(videofile)[ST_MTIME] <= os.stat(imagefile)[ST_MTIME]: return if imagefile.endswith('.raw'): imagefile += '.tmp' if popup: pop = gui.PopupBox( text='Creating thumbnail for "%s"...' % Unicode(os.path.basename(videofile)), width=osd.get_singleton().width - (config.OSD_OVERSCAN_LEFT + config.OSD_OVERSCAN_RIGHT) - 80) pop.show() args = [config.MPLAYER_CMD, videofile, imagefile] if pos != None: args.append(str(pos)) command = [ os.environ['FREEVO_SCRIPT'], '--execute=%s' % os.path.abspath(__file__) ] + args logger.debug(' '.join(command)) p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) (stdout, stderr) = p.communicate() if p.returncode: for line in stdout.split(): logger.debug(line) for line in stderr.split(): logger.info(line) if vfs.isfile(imagefile): try: image = Image.open(imagefile) if image.width > 255 or image.height > 255: image.thumbnail((255, 255)) mode = image.mode if mode == 'P': mode = 'RGB' if image.width * 3 > image.height * 4: # fix image with blank bars to be 4:3 nh = (image.width * 3) / 4 ni = Image.new((image.width, nh), from_format=image.mode) ni.draw_rectangle((0, 0), (image.width, nh), (0, 0, 0, 255), True) ni.blend(image, dst_pos=(0, (nh - image.height) / 2)) image = ni elif image.width * 3 < image.height * 4: # strange aspect, let's guess it's 4:3 new_size = (image.width, (image.width * 3) / 4) image = image.scale((new_size)) # crop some pixels, looks better that way image = image.crop((4, 3), (image.width - 8, image.height - 6)) mode = image.mode # Pygame can't handle BGRA images if mode == 'BGRA': mode = 'RGBA' if imagefile.endswith('.raw.tmp'): f = vfs.open(imagefile[:-4], 'w') data = (str(image.get_raw_data(format=mode)), image.size, mode) f.write('FRI%s%s%5s' % (chr(image.width), chr(image.height), mode)) f.write(data[0]) f.close() os.unlink(imagefile) else: image.save(imagefile) except (OSError, IOError), why: logger.error('snapshot: %s', why)
def loadbitmap(self, url, cache=False): """ Load a bitmap and return the pygame image object. """ if cache: if cache == True: cache = self.bitmapcache s = cache[url] if s: return s if not pygame.display.get_init(): return None try: if url.mode == 'BGRA': url.mode = 'RGBA' image = pygame.image.fromstring( str(url.get_raw_data(format=url.mode)), url.size, url.mode) except AttributeError: pass if url[:8] == 'thumb://': filename = os.path.abspath(url[8:]) thumbnail = True else: filename = os.path.abspath(url) thumbnail = False if not os.path.isfile(filename): filename = os.path.join(config.IMAGE_DIR, url[8:]) if not os.path.isfile(filename): print 'osd.py: Bitmap file "%s" doesn\'t exist!' % filename return None try: if isstring(filename) and filename.endswith('.raw'): # load cache data = util.read_thumbnail(filename) #self.printdata(data) # convert to pygame image image = pygame.image.fromstring(data[0], data[1], data[2]) elif thumbnail: # load cache or create it data = util.cache_image(filename) #self.printdata(data) # convert to pygame image try: image = pygame.image.fromstring( data[0], data[1], data[2]) except: data = util.create_thumbnail(filename) #self.printdata(data) image = pygame.image.fromstring( data[0], data[1], data[2]) else: try: image = pygame.image.load(filename) except pygame.error, e: print 'SDL image load problem: %s - trying Imaging' % e i = Image.open(filename) image = pygame.image.fromstring( i.tostring(), i.size, i.mode) except: print 'Problem while loading image %s' % String(url) if config.DEBUG: traceback.print_exc() return None except Exception, e: print 'image.fromstring:', e return None
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 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
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: if image.width > 255 or image.height > 255: image.thumbnail((255, 255)) #print 'thumb:', thumb #print 'image.mode:', image.mode if image.mode == 'P': image.mode = 'RGB'
def loadbitmap(self, url, cache=False): """ Load a bitmap and return the pygame image object. """ if cache: if cache == True: cache = self.bitmapcache s = cache[url] if s: return s if not pygame.display.get_init(): return None try: if url.mode == 'BGRA': url.mode = 'RGBA' image = pygame.image.fromstring(str(url.get_raw_data(format=url.mode)), url.size, url.mode) except AttributeError: pass if url[:8] == 'thumb://': filename = os.path.abspath(url[8:]) thumbnail = True else: filename = os.path.abspath(url) thumbnail = False if not os.path.isfile(filename): filename = os.path.join(config.IMAGE_DIR, url[8:]) if not os.path.isfile(filename): _debug_('Bitmap file "%s" doesn\'t exist!' % filename, DWARNING) #raise 'Bitmap file' return None try: if isstring(filename) and filename.endswith('.raw'): # load cache data = util.read_thumbnail(filename) #self.printdata(data) # convert to pygame image image = pygame.image.fromstring(data[0], data[1], data[2]) elif thumbnail: # load cache or create it data = util.cache_image(filename) #self.printdata(data) # convert to pygame image try: image = pygame.image.fromstring(data[0], data[1], data[2]) except: data = util.create_thumbnail(filename) #self.printdata(data) image = pygame.image.fromstring(data[0], data[1], data[2]) else: try: image = pygame.image.load(filename) except pygame.error, e: _debug_('SDL image load problem: %s - trying imlib2' % e, DINFO) try: i = Image.open(filename) image = pygame.image.fromstring(i.tostring(), i.size, i.mode) except IOError, why: _debug_('imlib2 image load problem: %s' % (why), DERROR)
import kaa.imlib2 as im import glob N = 1024 #for pic in glob.glob('/var/www/runat.me/tmp/maps/*/*/*.png'): for pic in glob.glob('/var/www/runat.me/tmp/maps/restore/*.png'): z = im.open(pic) if z.size == (N,N): b = z.scale((N/2,N/2)) b.save(pic)
from kaa import imlib2, display, main window = display.X11Window(size = (800, 600), title = "Kaa Display Test") image = imlib2.open("data/background.jpg") imlib2.add_font_path("data") image.draw_text((50, 50), "This is a Kaa Display Imlib2 Test", (255,255,255,255), "VeraBd/24") window.show() window.render_imlib2_image(image) main()
def crop_image(filename, region_width, region_height, x=0, y=0): image = imlib2.open(filename) image = image.crop((x, y), (region_width, region_height)) image.save(filename)
from kaa import imlib2, display import kaa window = display.X11Window(size=(800, 600), title="Kaa Display Test") image = imlib2.open("data/background.jpg") imlib2.add_font_path("data") image.draw_text((50, 50), "This is a Kaa Display Imlib2 Test", (255, 255, 255, 255), "VeraBd/24") window.show() window.render_imlib2_image(image) kaa.main.run()
class procstats(IdleBarPlugin): """ Retrieves information from /proc/stat and shows them in the idlebar. This plugin can show semi-accurate cpu usage stats and free memory in megabytes (calculated approx. as MemFree+Cached?) Activate with | plugin.activate('idlebar.system.procstats', level=20) for defaults or | plugin.activate('idlebar.system.procstats', level=20, args=(Mem, Cpu, Prec)) where - Mem: Draw memfree (default=1, -1 to disable) - Cpu: Draw cpuusage (default=1, -1 to disable) - Prec: Precision used when drawing cpu usage (default=1) """ def __init__(self, Mem=1, Cpu=1, Prec=1): IdleBarPlugin.__init__(self) self.drawCpu = Cpu self.drawMem = Mem self.precision = Prec self.time = 0 self.lastused = 0 self.lastuptime = 0 def config(self): return [ ('SENSORS_PLATFORM_PATH', '/sys/devices/platform', 'path to the sensor devices'), ('SENSORS_I2CDEV_PATH', '/sys/bus/i2c/devices', 'path to the i2c devices'), ] def getStats(self): """ Don't get the stats for each update as it gets annoying while navigating Update maximum every 10 seconds """ if (time.time() - self.time) > 10: self.time = time.time() if self.drawMem == 1: self.getMemUsage() if self.drawCpu == 1: self.getCpuUsage() def getMemUsage(self): """ May not be correct, but i like to see total free mem as freemem+cached """ free = 0 meminfo = None try: meminfo = file('/proc/meminfo', 'r').read().strip() except OSError: logger.warning( '[procstats]: The file /proc/meminfo is not available') if meminfo: i = 0 meminfo = meminfo.split() for l in meminfo: if l in ['MemFree:', 'Buffers:', 'Cached:']: free += int(meminfo[i + 1]) i += 1 self.currentMem = _('%iM') % (free / 1024) def getCpuUsage(self): """ This could/should maybe be an even more advanced algorithm, but it will suffice for normal use. Note: cpu defined as 'cpu <user> <nice> <system> <idle>' at first line in /proc/stat """ uptime = 0 used = 0 f = open('/proc/stat') if f: stat = string.split(f.readline()) used = long(stat[1]) + long(stat[2]) + long(stat[3]) uptime = used + long(stat[4]) f.close() usage = (float(used - self.lastused) / float(uptime - self.lastuptime)) * 100 self.lastuptime = uptime self.lastused = used self.currentCpu = _('%s%%') % round(usage, self.precision) def draw(self, (type, object), x, osd): try: self.getStats() except: logger.debug( '[procstats]: Not working, this plugin is only tested with 2.4 and 2.6 kernels' ) font = osd.get_font(config.OSD_IDLEBAR_FONT) widthtot = 0 if self.drawCpu == 1: image_file = os.path.join(config.ICON_DIR, 'misc', 'cpu.png') w, h = imlib2.open(image_file).size text_w = font.stringsize(self.currentCpu) (image_x, image_y, text_x, text_y, width) = calc_positions(osd, w, h, text_w, font.h) osd.draw_image(image_file, (x + image_x, image_y, -1, -1)) osd.write_text(self.currentCpu, font, None, x + text_x, text_y, text_w, font.h, 'center', 'top') widthtot += width + 5 x += width + 5 if self.drawMem == 1: image_file = os.path.join(config.ICON_DIR, 'misc', 'memory.png') w, h = imlib2.open(image_file).size text_w = font.stringsize(self.currentMem) (image_x, image_y, text_x, text_y, width) = calc_positions(osd, w, h, text_w, font.h) osd.draw_image(image_file, (x + image_x, image_y, -1, -1)) osd.write_text(self.currentMem, font, None, x + text_x, text_y, text_w, font.h, 'center', 'top') widthtot += width + 5 x += width + 5 return widthtot - 5
def snapshot(videofile, imagefile=None, pos=None, update=True, popup=None): """ make a snapshot of the videofile at position pos to imagefile """ from subprocess import Popen, PIPE import kaa.imlib2 as Image import vfs import gui.PopupBox import osd # skip broken symlinks if os.path.islink(videofile) and not os.path.exists(videofile): return if not imagefile: imagefile = vfs.getoverlay(videofile + '.raw') if not update and os.path.isfile(imagefile) and \ os.stat(videofile)[ST_MTIME] <= os.stat(imagefile)[ST_MTIME]: return if imagefile.endswith('.raw'): imagefile += '.tmp' if popup: pop = gui.PopupBox(text='Creating thumbnail for "%s"...' % Unicode(os.path.basename(videofile)), width=osd.get_singleton().width-(config.OSD_OVERSCAN_LEFT+config.OSD_OVERSCAN_RIGHT)-80) pop.show() args = [ config.MPLAYER_CMD, videofile, imagefile ] if pos != None: args.append(str(pos)) command = [os.environ['FREEVO_SCRIPT'], '--execute=%s' % os.path.abspath(__file__) ] + args logger.debug(' '.join(command)) p = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) (stdout, stderr) = p.communicate() if p.returncode: for line in stdout.split(): logger.debug(line) for line in stderr.split(): logger.info(line) if vfs.isfile(imagefile): try: image = Image.open(imagefile) if image.width > 255 or image.height > 255: image.thumbnail((255,255)) mode = image.mode if mode == 'P': mode = 'RGB' if image.width * 3 > image.height * 4: # fix image with blank bars to be 4:3 nh = (image.width*3)/4 ni = Image.new((image.width, nh), from_format=image.mode) ni.draw_rectangle((0,0), (image.width, nh), (0,0,0,255), True) ni.blend(image, dst_pos=(0,(nh- image.height) / 2)) image = ni elif image.width * 3 < image.height * 4: # strange aspect, let's guess it's 4:3 new_size = (image.width, (image.width*3)/4) image = image.scale((new_size)) # crop some pixels, looks better that way image = image.crop((4, 3), (image.width-8, image.height-6)) mode = image.mode # Pygame can't handle BGRA images if mode == 'BGRA': mode = 'RGBA' if imagefile.endswith('.raw.tmp'): f = vfs.open(imagefile[:-4], 'w') data = (str(image.get_raw_data(format=mode)), image.size, mode) f.write('FRI%s%s%5s' % (chr(image.width), chr(image.height), mode)) f.write(data[0]) f.close() os.unlink(imagefile) else: image.save(imagefile) except (OSError, IOError), why: logger.error('snapshot: %s', why)
def snapshot(videofile, imagefile=None, pos=None, update=True, popup=None): """ make a snapshot of the videofile at position pos to imagefile """ import config import popen3 import kaa.imlib2 as Image import util import vfs import gui.PopupBox import osd if not imagefile: imagefile = vfs.getoverlay(videofile + '.raw') if not update and os.path.isfile(imagefile) and \ os.stat(videofile)[ST_MTIME] <= os.stat(imagefile)[ST_MTIME]: return if imagefile.endswith('.raw'): imagefile += '.tmp' if popup: pop = gui.PopupBox(text='Creating thumbnail for \'%s\'...' % \ Unicode(os.path.basename(videofile)), width=osd.get_singleton().width-config.OSD_OVERSCAN_X*2-80) pop.show() args = [ config.MPLAYER_CMD, videofile, imagefile ] if pos != None: args.append(str(pos)) out = popen3.stdout([os.environ['FREEVO_SCRIPT'], 'execute', os.path.abspath(__file__) ] + args) if out: for line in out: print line if vfs.isfile(imagefile): try: image = Image.open(imagefile) if image.width > 255 or image.height > 255: image.thumbnail((255,255)) if image.mode == 'P': image.mode = 'RGB' if image.width * 3 > image.height * 4: # fix image with blank bars to be 4:3 nh = (image.width*3)/4 ni = Image.new((image.width, nh), from_format = image.mode) ni.draw_rectangle((0,0), (image.width, nh), (0,0,0,255), True) ni.blend(image, dst_pos=(0,(nh- image.height) / 2)) image = ni elif image.width * 3 < image.height * 4: # strange aspect, let's guess it's 4:3 new_size = (image.width, (image.width*3)/4) image = image.scale((new_size)) # crop some pixels, looks better that way image = image.crop((4, 3), (image.width-8, image.height-6)) # Pygame can't handle BGRA images if image.mode == 'BGRA': image.mode = 'RGBA' if imagefile.endswith('.raw.tmp'): f = vfs.open(imagefile[:-4], 'w') data = (str(image.get_raw_data(format=image.mode)), image.size, image.mode) f.write('FRI%s%s%5s' % (chr(image.width), chr(image.height), image.mode)) f.write(data[0]) f.close() os.unlink(imagefile) else: image.save(imagefile) except (OSError, IOError), e: print 'snapshot:', e
""" Draw the sensors in the idlebar @returns: the space taken by the images @rtype: int """ widthtot = 0 font = osd.get_font(config.OSD_IDLEBAR_FONT) if self.hotstack: font.color = 0xff0000 elif not self.hotstack and font.color == 0xff0000: font.color = 0xffffff text = self.cpu.temp() image_file = os.path.join(config.ICON_DIR, 'misc', 'cpu.png') w, h = imlib2.open(image_file).size text_w = font.stringsize(text) (image_x, image_y, text_x, text_y, width) = calc_positions(osd, w, h, text_w, font.h) osd.draw_image(image_file, (x + image_x, image_y, -1, -1)) osd.write_text(text, font, None, x + text_x, text_y, text_w, font.h, 'center', 'top') widthtot += width + 5 x += width + 5 if self.case: text = self.case.temp() image_file = os.path.join(config.ICON_DIR, 'misc', 'case.png') w, h = imlib2.open(image_file).size text_w = font.stringsize(text) (image_x, image_y, text_x, text_y,