Convert ImageData to PIL Image.

    .. note:: Image resources contain extra alpha channels in these keys:
        `ALPHA_NAMES_UNICODE`, `ALPHA_NAMES_PASCAL`, `ALPHA_IDENTIFIERS`.
967248
def convert_image_data_to_pil(psd, apply_icc=True, **kwargs):
    
    from PIL import Image, ImageOps
    header = psd.header
    size = (header.width, header.height)
    channels = []
    for channel_data in psd.image_data.get_data(header):
        channels.append(_create_channel(size, channel_data, header.depth))
    alpha = _get_alpha_use(psd)
    mode = get_pil_mode(header.color_mode.name)
    if mode == 'P':
        image = Image.merge('L', channels[:get_pil_channels(mode)])
        image.putpalette(psd.color_mode_data.interleave())
    elif mode == 'MULTICHANNEL':
        image = channels[0]  # Multi-channel mode is a collection of alpha.
    else:
        image = Image.merge(mode, channels[:get_pil_channels(mode)])
    if mode == 'CMYK':
        image = image.point(lambda x: 255 - x)
    if apply_icc and 'ICC_PROFILE' in psd.image_resources:
        image = _apply_icc(image, psd.image_resources.get_data('ICC_PROFILE'))
    if alpha and mode in ('L', 'RGB'):
        image.putalpha(channels[-1])
    return _remove_white_background(image)
467346
def to_image_type(image_type):
    '''
        
    '''
    if image_type is None: return None
    if isinstance(image_type, type) and issubclass(image_type, ImageType): return image_type
    if pimms.is_str(image_type):
        image_type = image_type.lower()
        if image_type in image_types_by_name: return image_types_by_name[image_type]
        for it in image_types:
            if image_type in it.aliases(): return it
        raise ValueError('"%s" is not a valid image-type name or alias' % image_type)
    for x in (image_type, type(image_type)):
        try:    return image_types_by_image_type[x]
        except Exception: pass
        try:    return image_types_by_header_type[x]
        except Exception: pass
    raise ValueError('Unsupported image type: %s' % image_type)
131660
def image(self, name, x=None, y=None, w=0,h=0,type='',link=''):
        ""
        if not name in self.images:
            #First use of image, get info
            if(type==''):
                pos=name.rfind('.')
                if(not pos):
                    self.error('image file has no extension and no type was specified: '+name)
                type=substr(name,pos+1)
            type=type.lower()
            if(type=='jpg' or type=='jpeg'):
                info=self._parsejpg(name)
            elif(type=='png'):
                info=self._parsepng(name)
            else:
                #Allow for additional formats
                #maybe the image is not showing the correct extension,
                #but the header is OK,
                succeed_parsing = False
                #try all the parsing functions
                parsing_functions = [self._parsejpg,self._parsepng,self._parsegif]
                for pf in parsing_functions:
                    try:
                        info = pf(name)
                        succeed_parsing = True
                        break;
                    except:
                        pass
                #last resource
                if not succeed_parsing:
                    mtd='_parse'+type
                    if not hasattr(self,mtd):
                        self.error('Unsupported image type: '+type)
                    info=getattr(self, mtd)(name)
                mtd='_parse'+type
                if not hasattr(self,mtd):
                    self.error('Unsupported image type: '+type)
                info=getattr(self, mtd)(name)
            info['i']=len(self.images)+1
            self.images[name]=info
        else:
            info=self.images[name]
        #Automatic width and height calculation if needed
        if(w==0 and h==0):
            #Put image at 72 dpi
            w=info['w']/self.k
            h=info['h']/self.k
        elif(w==0):
            w=h*info['w']/info['h']
        elif(h==0):
            h=w*info['h']/info['w']
        # Flowing mode
        if y is None:
            if (self.y + h > self.page_break_trigger and not self.in_footer and self.accept_page_break()):
                #Automatic page break
                x = self.x
                self.add_page(self.cur_orientation)
                self.x = x
            y = self.y
            self.y += h
        if x is None:
            x = self.x
        self._out(sprintf('q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q',w*self.k,h*self.k,x*self.k,(self.h-(y+h))*self.k,info['i']))
        if(link):
            self.link(x,y,w,h,link)
758399
def to_color(self):
        
        color_data = np.zeros([self.height, self.width, 3])
        color_data[:, :, 0] = self.data
        color_data[:, :, 1] = self.data
        color_data[:, :, 2] = self.data
        return ColorImage(color_data.astype(np.uint8), self._frame)
1158049
def fig_to_src(figure, image_format='png', dpi=80):
    
    if image_format == 'png':
        f = io.BytesIO()
        figure.savefig(f, format=image_format, dpi=dpi)
        f.seek(0)
        return png_to_src(f.read())

    elif image_format == 'svg':
        f = io.StringIO()
        figure.savefig(f, format=image_format, dpi=dpi)
        f.seek(0)
        return svg_to_src(f.read())
182720
def get_imageblock(filename, format=''):
    
    _, extension = os.path.splitext(filename)

    with open(filename, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read()).decode('utf-8')

    return '\n\n.. raw:: html\n\n\t<img src="data:image/' + (format if format else extension[1:]) + ';base64,' + encoded_string +'">\n'
1336738
def checkImages(images):
    
    # Init results
    images2 = []

    for im in images:
        if PIL and isinstance(im, PIL.Image.Image):
            # We assume PIL images are allright
            images2.append(im)

        elif np and isinstance(im, np.ndarray):
            # Check and convert dtype
            if im.dtype == np.uint8:
                images2.append(im)  # Ok
            elif im.dtype in [np.float32, np.float64]:
                im = im.copy()
                im[im < 0] = 0
                im[im > 1] = 1
                im *= 255
                images2.append(im.astype(np.uint8))
            else:
                im = im.astype(np.uint8)
                images2.append(im)
            # Check size
            if im.ndim == 2:
                pass  # ok
            elif im.ndim == 3:
                if im.shape[2] not in [3, 4]:
                    raise ValueError('This array can not represent an image.')
            else:
                raise ValueError('This array can not represent an image.')
        else:
            raise ValueError('Invalid image type: ' + str(type(im)))

    # Done
    return images2
940583
def pil_image(self):
        
        channels, fill_value = self._finalize()

        if self.is_empty():
            return Pil.new(self.mode, (0, 0))

        if self.mode == "L":
            if fill_value is not None:
                img = Pil.fromarray(channels[0].filled(fill_value))
            else:
                img = Pil.fromarray(channels[0].filled(0))
                alpha = np.zeros(channels[0].shape, np.uint8)
                mask = np.ma.getmaskarray(channels[0])
                alpha = np.where(mask, alpha, 255)
                pil_alpha = Pil.fromarray(alpha)

                img = Pil.merge("LA", (img, pil_alpha))
        elif self.mode == "LA":
            if fill_value is not None:
                img = Pil.fromarray(channels[0].filled(fill_value))
                pil_alpha = Pil.fromarray(channels[1])
            else:
                img = Pil.fromarray(channels[0].filled(0))
                alpha = np.zeros(channels[0].shape, np.uint8)
                mask = np.ma.getmaskarray(channels[0])
                alpha = np.where(mask, alpha, channels[1])
                pil_alpha = Pil.fromarray(alpha)
            img = Pil.merge("LA", (img, pil_alpha))

        elif self.mode == "RGB":
            # Mask where all channels have missing data (incomplete data will
            # be shown).
            mask = (np.ma.getmaskarray(channels[0]) &
                    np.ma.getmaskarray(channels[1]) &
                    np.ma.getmaskarray(channels[2]))

            if fill_value is not None:
                pil_r = Pil.fromarray(channels[0].filled(fill_value[0]))
                pil_g = Pil.fromarray(channels[1].filled(fill_value[1]))
                pil_b = Pil.fromarray(channels[2].filled(fill_value[2]))
                img = Pil.merge("RGB", (pil_r, pil_g, pil_b))
            else:
                pil_r = Pil.fromarray(channels[0].filled(0))
                pil_g = Pil.fromarray(channels[1].filled(0))
                pil_b = Pil.fromarray(channels[2].filled(0))

                alpha = np.zeros(channels[0].shape, np.uint8)
                alpha = np.where(mask, alpha, 255)
                pil_a = Pil.fromarray(alpha)

                img = Pil.merge("RGBA", (pil_r, pil_g, pil_b, pil_a))

        elif self.mode == "RGBA":
            # Mask where all channels have missing data (incomplete data will
            # be shown).
            mask = (np.ma.getmaskarray(channels[0]) &
                    np.ma.getmaskarray(channels[1]) &
                    np.ma.getmaskarray(channels[2]) &
                    np.ma.getmaskarray(channels[3]))

            if fill_value is not None:
                pil_r = Pil.fromarray(channels[0].filled(fill_value[0]))
                pil_g = Pil.fromarray(channels[1].filled(fill_value[1]))
                pil_b = Pil.fromarray(channels[2].filled(fill_value[2]))
                pil_a = Pil.fromarray(channels[3].filled(fill_value[3]))
                img = Pil.merge("RGBA", (pil_r, pil_g, pil_b, pil_a))
            else:
                pil_r = Pil.fromarray(channels[0].filled(0))
                pil_g = Pil.fromarray(channels[1].filled(0))
                pil_b = Pil.fromarray(channels[2].filled(0))

                alpha = np.where(mask, 0, channels[3])
                pil_a = Pil.fromarray(alpha)

                img = Pil.merge("RGBA", (pil_r, pil_g, pil_b, pil_a))

        else:
            raise TypeError("Does not know how to use mode %s." % (self.mode))

        return img
733499
def image_data(verbose=False):
  """"""
  # This is a principled use of the `global` statement; don't lint me.
  global _IMAGE_DATA  # pylint: disable=global-statement
  if _IMAGE_DATA is None:
    if verbose:
      logger.info("--- Downloading image.")
    with contextlib.closing(urllib.request.urlopen(IMAGE_URL)) as infile:
      _IMAGE_DATA = infile.read()
  return _IMAGE_DATA
921138
def guessImageMetadataFromData(img_data):
    
    format, width, height = None, None, None
    img_stream = io.BytesIO(img_data)
    try:
      img = PIL.Image.open(img_stream)
    except IOError:
      format = imghdr.what(None, h=img_data)
      format = SUPPORTED_IMG_FORMATS.get(format, None)
    else:
      format = img.format.lower()
      format = SUPPORTED_IMG_FORMATS.get(format, None)
      width, height = img.size
    return format, width, height
902224
def _image_url(image, dst_color=None, src_color=None):
    
    if src_color and dst_color:
        if not Image:
            raise Exception("Images manipulation require PIL")
    file = StringValue(image).value
    path = None
    if callable(STATIC_ROOT):
        try:
            _file, _storage = list(STATIC_ROOT(file))[0]
            d_obj = _storage.modified_time(_file)
            filetime = int(time.mktime(d_obj.timetuple()))
            if dst_color:
                path = _storage.open(_file)
        except:
            filetime = 'NA'
    else:
        _path = os.path.join(STATIC_ROOT, file)
        if os.path.exists(_path):
            filetime = int(os.path.getmtime(_path))
            if dst_color:
                path = open(_path, 'rb')
        else:
            filetime = 'NA'
    BASE_URL = STATIC_URL
    if path:
        src_color = tuple(int(round(c)) for c in ColorValue(
            src_color).value[:3]) if src_color else (0, 0, 0)
        dst_color = [int(round(c)) for c in ColorValue(dst_color).value[:3]]

        file_name, file_ext = os.path.splitext(
            os.path.normpath(file).replace('\\', '_').replace('/', '_'))
        key = (filetime, src_color, dst_color)
        key = file_name + '-' + base64.urlsafe_b64encode(
            hashlib.md5(repr(key)).digest()).rstrip('=').replace('-', '_')
        asset_file = key + file_ext
        asset_path = os.path.join(ASSETS_ROOT, asset_file)

        if os.path.exists(asset_path):
            file = asset_file
            BASE_URL = ASSETS_URL
            filetime = int(os.path.getmtime(asset_path))
        else:
            image = Image.open(path)
            image = image.convert("RGBA")
            pixdata = image.load()
            for y in xrange(image.size[1]):
                for x in xrange(image.size[0]):
                    if pixdata[x, y][:3] == src_color:
                        new_color = tuple(dst_color + [pixdata[x, y][3]])
                        pixdata[x, y] = new_color
            try:
                image.save(asset_path)
                file = asset_file
                BASE_URL = ASSETS_URL
            except IOError:
                log.exception("Error while saving image")
    url = 'url("%s%s?_=%s")' % (BASE_URL, file, filetime)
    return StringValue(url)
429989
def get_pil_mode(value, alpha=False):
    """"""
    name = {
        'GRAYSCALE': 'L',
        'BITMAP': '1',
        'DUOTONE': 'L',
        'INDEXED': 'P',
    }.get(value, value)
    if alpha and name in ('L', 'RGB'):
        name += 'A'
    return name
259924
def convert_thumbnail_to_pil(thumbnail, mode='RGB'):
    """"""
    from PIL import Image
    if thumbnail.fmt == 0:
        size = (thumbnail.width, thumbnail.height)
        stride = thumbnail.widthbytes
        return Image.frombytes('RGBX', size, thumbnail.data, 'raw', mode,
                                stride)
    elif thumbnail.fmt == 1:
        return Image.open(io.BytesIO(thumbnail.data))
    else:
        raise ValueError('Unknown thumbnail format %d' % (thumbnail.fmt))
874645
def display_pil_image(im):
   """"""
   from IPython.core import display
   b = BytesIO()
   im.save(b, format='png')
   data = b.getvalue()

   ip_img = display.Image(data=data, format='png', embed=True)
   return ip_img._repr_png_()
62730
def _repr_png_(self):
        

        data = ffi.new('l_uint8 **')
        size = ffi.new('size_t *')

        err = lept.pixWriteMemPng(data, size, self._cdata, 0)
        if err != 0:
            raise LeptonicaIOError("pixWriteMemPng")

        char_data = ffi.cast('char *', data[0])
        return ffi.buffer(char_data, size[0])[:]
48430
def to_png
      return @png_data if !@png_data.nil?
      image = minimagick_image
      image.resize '16x16!'
      image.format 'png'
      image.strip
      @png_data = image.to_blob
      raise FaviconParty::InvalidData.new("Empty png") if @png_data.empty?
      @png_data
    end
1307108
def toPIL(self, **attribs):
        
        import PIL.Image
        bytes = self.convert("png")
        sfile = io.BytesIO(bytes)
        pil = PIL.Image.open(sfile)
        return pil