def pygamesurface_imlib2_scale(image, newsize): buf = pygame.image.tostring(image, 'RGBA') im2 = imlib2.new(image.get_size(), buf) scaled_im2 = im2.scale(newsize) buf = str(scaled_im2.get_raw_data('BGRA')) return pygame.image.frombuffer(buf, newsize, 'RGBA')
def draw(self): img = imlib2.new((self.width, self.height)) img.clear() for child in self.children: try: child.draw(img, self.info_dict) except: osd_skin.report_error('Caught exception while processing OSD element!' + traceback.format_exc()) return img
def _blit(self, img, r): pos, size = r if isinstance(img, mevas.imagelib.get_backend("imlib2").Image): self.__render(img._image, pos, pos, size, self._dither, self._blend) else: if img.size != size: img = imagelib.crop(img, pos, size) data = img.get_raw_data("RGB") img = imlib2.new( size, data, "RGB" ) self.__render(img._image, pos, dither = self._dither, blend = self._blend)
def draw(self): img = imlib2.new((self.width, self.height)) img.clear() for child in self.children: try: obj = copy.copy(child.get_skin_object()) x = osd_skin.eval_or_int(obj.pos[0], self.info_dict) y = osd_skin.eval_or_int(obj.pos[1], self.info_dict) w = osd_skin.eval_or_int(obj.size[0], self.info_dict) h = osd_skin.eval_or_int(obj.size[1], self.info_dict) obj.pos = (x,y) obj.size = (w,h) obj.prepare() obj.render(img, self.info_dict) obj.finish() except: traceback.print_exc() return img
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 prepare(self): # Load background image self.image = imlib2.new(self.size) for obj in self.objects: obj.prepare()
if key == 's': global shaped shaped = not shaped if shaped: window.set_shape_mask_from_imlib2_image(image, (0,0)) else: window.reset_shape_mask() def mapped(): window.focus() window = display.X11Window(size = (800, 600), title = "Kaa Display Test") imlib2.add_font_path("data") image = imlib2.new((800,600)) image.clear() image.draw_ellipse((400,300), (400, 300), (0,0,255,128)) image.draw_text((10, 50), "This is a Kaa Display Shaped Window Test", (255,255,255,255), "VeraBd/24") window.signals['expose_event'].connect(redraw) window.signals['key_press_event'].connect(key_pressed) window.signals['map_event'].connect(mapped) window.set_decorated(decorated) window.set_shape_mask_from_imlib2_image(image, (0,0)) window.show() print 'Shaped window test app' print 'Use the following keys to test features'
def new(size, rawdata = None, from_format = "BGRA"): if from_format not in _capabilities["from-raw-formats"]: raise ValueError, "Unsupported raw format: %s" % from_format return Image( imlib2.new(size, rawdata, from_format) )
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)
window.focus() if x11.get_display().composite_supported(): composite = True else: print 'Compositing not supported on this display!' sys.exit(1) window = display.X11Window(size=(800, 600), title="Kaa Display Test", composite=composite) imlib2.add_font_path("data") image = imlib2.new((800, 600)) image.clear() image.draw_ellipse((400, 300), (400, 300), (0, 0, 255, 128)) image.draw_text((10, 50), "This is a Kaa Display Composited Window Test", (255, 255, 255, 255), "VeraBd/24") window.signals['expose_event'].connect(redraw) window.signals['key_press_event'].connect(key_pressed) window.signals['map_event'].connect(mapped) window.set_decorated(decorated) window.show() print 'Shaped window test app' print 'Use the following keys to test features' print 'Esc or q = Quit'
__all__ = [ 'Text' ] from object import * from kaa.strutils import unicode_to_str from kaa import evas import time try: from kaa import imlib2 # Construct a gradient (white to black) image used for fading # out text that has clip set. line = "" for b in range(255, 0, -7) + [0]: line += chr(b)*4 _text_fadeout_mask = imlib2.new((len(line)/4, 100), line * 100) del line except ImportError: imlib2 = None class Text(Object): def __init__(self, text = None, font = None, size = None, color = None): super(Text, self).__init__() for prop in ("size", "pos", "clip"): self._supported_sync_properties.remove(prop) self._supported_sync_properties += [ "clip", "font", "text", "size", "pos" ] # Clip to parent by default. self["clip"] = "auto"
def prepare(self): self.image = imlib2.new(self.size) self.first_render = True
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
def _render_text_to_image(self, force = True): if not self._font or self["text"] == None: return t0=time.time() metrics = self._font.get_text_size(self["text"]) # Create image size based on horizontal advance and vertical height. w, h = metrics[2], metrics[1] draw_mask = False if self["clip"] == "auto": extents = self._get_extents() if self["size"] != ("auto", "auto"): computed_size = self._get_computed_size() if self["size"][0] != "auto": extents[0] = min(extents[0], computed_size[0]) if self["size"][1] != "auto": extents[1] = min(extents[1], computed_size[1]) if extents[0] < w: w = extents[0] draw_mask = True h = min(h, extents[1]) if w <= 0 or h <= 0: return if self._img and (w, h) == self._img.size: if not force: return i = self._img i.clear() self._dirty_cached_value("size") else: i = imlib2.new((w, h)) # Need to append " " to work around a bug in Imlib2 1.2.1.004 and # earlier. padding = self._get_computed_padding() i.draw_text((padding[3], padding[1]), self["text"] + " ", (255,255,255,255), self._font) # DISCHI: bug here. The code would draw the mask at a negative x value if # i.size[0] < _text_fadeout_mask.size[0] and this does not work. So now we # use max(0, value) to avoid that, but this is not correct in the way it looks. if draw_mask: for y in range(0, i.size[1], _text_fadeout_mask.size[1]): i.draw_mask(_text_fadeout_mask, (max(0, i.size[0] - _text_fadeout_mask.size[0]), y)) self._o.size_set(i.size) buf = i.get_raw_data() evas.data_argb_premul(buf) self._o.data_set(buf, copy = False) self._o.resize(i.size) self._o.fill_set((0, 0), i.size) self._o.alpha_set(True) self._o.pixels_dirty_set() self._img = i self._remove_sync_property("font") self._remove_sync_property("text") self._remove_sync_property("clip")