Better transformation from pil.image to gtk pixbuf (see last commit)
This commit is contained in:
		
							parent
							
								
									3c704f95da
								
							
						
					
					
						commit
						88d4826693
					
				
					 1 changed files with 33 additions and 23 deletions
				
			
		| 
						 | 
				
			
			@ -42,6 +42,7 @@ try:
 | 
			
		|||
except:
 | 
			
		||||
    pass
 | 
			
		||||
from io import BytesIO
 | 
			
		||||
import array
 | 
			
		||||
 | 
			
		||||
import logging
 | 
			
		||||
log = logging.getLogger('gajim.gtkgui_helpers')
 | 
			
		||||
| 
						 | 
				
			
			@ -417,22 +418,31 @@ def get_abspath_for_script(scriptname, want_type = False):
 | 
			
		|||
    else:
 | 
			
		||||
        return path_to_script
 | 
			
		||||
 | 
			
		||||
# see http://stackoverflow.com/a/8892894/3528174
 | 
			
		||||
# and https://developer.gnome.org/gdk-pixbuf/unstable/gdk-pixbuf-Image-Data-in-Memory.html#gdk-pixbuf-new-from-bytes
 | 
			
		||||
def pillow2pixbuf(im):
 | 
			
		||||
    arr = array.array('B', im.tobytes())
 | 
			
		||||
    width, height = im.size
 | 
			
		||||
    return GdkPixbuf.Pixbuf.new_from_data(arr, GdkPixbuf.Colorspace.RGB,
 | 
			
		||||
                                          False, 8, width, height, width * 3)
 | 
			
		||||
 | 
			
		||||
def get_pixbuf_from_data(file_data, want_type = False):
 | 
			
		||||
    """
 | 
			
		||||
    Get image data and returns GdkPixbuf.Pixbuf if want_type is True it also
 | 
			
		||||
    returns 'jpeg', 'png' etc
 | 
			
		||||
    """
 | 
			
		||||
    pixbufloader = GdkPixbuf.PixbufLoader()
 | 
			
		||||
    # try to open and convert every image format supported by PILLOW to png format
 | 
			
		||||
    try:
 | 
			
		||||
        avatar = Image.open(BytesIO(file_data)).convert("RGB")
 | 
			
		||||
        output = BytesIO()
 | 
			
		||||
        avatar.save(output, format='PNG')
 | 
			
		||||
        file_data = output.getvalue()
 | 
			
		||||
        output.close()
 | 
			
		||||
        im = Image.open(BytesIO(file_data)).convert("RGB")
 | 
			
		||||
        pixbuf = pillow2pixbuf(im)
 | 
			
		||||
        if want_type:
 | 
			
		||||
            typ = "png"
 | 
			
		||||
            return pixbuf, typ
 | 
			
		||||
        else:
 | 
			
		||||
            return pixbuf
 | 
			
		||||
    except:
 | 
			
		||||
        log.debug("Could not use pillow to convert avatar image (this is non fatal)")
 | 
			
		||||
        pass        # this didn't work, so just use the old gtk code to import the image
 | 
			
		||||
        log.info("Could not use pillow to convert avatar image to pixbuf, trying pixbufloader instead...")
 | 
			
		||||
        pixbufloader = GdkPixbuf.PixbufLoader()
 | 
			
		||||
        try:
 | 
			
		||||
            pixbufloader.write(file_data)
 | 
			
		||||
            pixbufloader.close()
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
		Loading…
	
	Add table
		
		Reference in a new issue