Create a data URL representing an image from a PIL.Image.

  Args:
    image: a numpy
    mode: presently only supports "data" for data URL

  Returns:
    URL representing image
431697
def _image_url(array, fmt='png', mode="data", quality=90, domain=None):
  
  supported_modes = ("data")
  if mode not in supported_modes:
    message = "Unsupported mode '%s', should be one of '%s'."
    raise ValueError(message, mode, supported_modes)

  image_data = serialize_array(array, fmt=fmt, quality=quality)
  base64_byte_string = base64.b64encode(image_data).decode('ascii')
  return "data:image/" + fmt.upper() + ";base64," + base64_byte_string
1079124
def __get_img(self):
        
        with self.fs.open(self.__img_path, 'rb') as fd:
            img = PIL.Image.open(fd)
            img.load()
            return img
278330
def display(self, image):
        
        assert(image.mode == self.mode)
        assert(image.size == self.size)

        image = self.preprocess(image)

        self.command(
            # Column start/end address
            self._const.COLUMNADDR, self._colstart, self._colend - 1,
            # Page start/end address
            self._const.PAGEADDR, 0x00, self._pages - 1)

        buf = bytearray(self._w * self._pages)
        off = self._offsets
        mask = self._mask

        idx = 0
        for pix in image.getdata():
            if pix > 0:
                buf[off[idx]] |= mask[idx]
            idx += 1

        self.data(list(buf))
1209389
def image(self, image):
        
        if image.mode != '1':
            raise ValueError('Image must be in mode 1.')
        imwidth, imheight = image.size
        if imwidth != self.width or imheight != self.height:
            raise ValueError('Image must be same dimensions as display ({0}x{1}).' \
                .format(self.width, self.height))
        # Grab all the pixels from the image, faster than getpixel.
        pix = image.load()
        # Iterate through the memory pages
        index = 0
        for page in range(self._pages):
            # Iterate through all x axis columns.
            for x in range(self.width):
                # Set the bits for the column of pixels at the current position.
                bits = 0
                # Don't use range here as it's a bit slow
                for bit in [0, 1, 2, 3, 4, 5, 6, 7]:
                    bits = bits << 1
                    bits |= 0 if pix[(x, page*8+7-bit)] == 0 else 1
                # Update buffer byte and increment to next byte.
                self._buffer[index] = bits
                index += 1
159760
def from_image(cls, image, filename):
        

        source = Image.open(BytesIO(image))
        source = source.convert('1')
        width = int(math.ceil(source.size[0] / 8.0))

        data = []
        for line in _chunked(list(source.getdata()), source.size[0]):
            row = ''.join(['0' if p else '1' for p in line])
            row = row.ljust(width * 8, '0')
            data.append(row)
        data = GRFData(width, bin=''.join(data))

        return cls(filename, data)
38300
def from_dict(raw_data):
        """"""
        url = None
        width = None
        height = None
        try:
            url = raw_data['url']
            width = raw_data['width']
            height = raw_data['height']
        except KeyError:
            raise ValueError('Unexpected image json structure')
        except TypeError:
            # Happens when raw_data is None, i.e. when a term has no image:
            pass
        return Image(url, width, height)
822194
def download_image(self, img_url):
        
        img_request = None
        try:
            img_request = requests.request(
                'get', img_url, stream=True, proxies=self.proxies)
            if img_request.status_code != 200:
                raise ImageDownloadError(img_request.status_code)
        except:
            raise ImageDownloadError()

        if img_url[-3:] == "svg" or (int(img_request.headers['content-length']) > self.min_filesize and\
                                     int(img_request.headers['content-length']) < self.max_filesize):
            img_content = img_request.content
            with open(os.path.join(self.download_path, img_url.split('/')[-1]), 'wb') as f:
                byte_image = bytes(img_content)
                f.write(byte_image)
        else:
            raise ImageSizeError(img_request.headers['content-length'])
        return True
1319360
def locate(self, image):
        
        from .entity import Image
        if not isinstance(image, Image):
            raise TypeError('image must be a sqlalchemy_imageattach.entity.'
                            'Image instance, not ' + repr(image))
        url = self.get_url(image.object_type, image.object_id,
                           image.width, image.height, image.mimetype)
        if '?' in url:
            fmt = '{0}&_ts={1}'
        else:
            fmt = '{0}?_ts={1}'
        return fmt.format(url, image.created_at.strftime('%Y%m%d%H%M%S%f'))
664866
def display(self, image):
        
        assert(image.size == self.size)

        self.image = self.preprocess(image).copy()
1044814
def show(data, negate=False):
    
    from PIL import Image as pil
    data = np.array((data - data.min()) * 255.0 /
                    (data.max() - data.min()), np.uint8)
    if negate:
        data = 255 - data
    img = pil.fromarray(data)
    img.show()
706382
def pull_image(self, image):
        
        def callback(msg):
            self.project.emit("log.info", {"message": msg})
        yield from self.manager.pull_image(image, progress_callback=callback)
418610
def wrap(self, image):
        
        if hasattr(image, 'size') and hasattr(image, 'convert'):
            # Treat image as PIL/pillow Image object
            self.width, self.height = image.size
            array_type = ctypes.c_ubyte * 4 * (self.width * self.height)
            self.pixels_array = array_type()
            pixels = image.convert('RGBA').getdata()
            for i, pixel in enumerate(pixels):
                self.pixels_array[i] = pixel
        else:
            self.width, self.height, pixels = image
            array_type = ctypes.c_ubyte * 4 * self.width * self.height
            self.pixels_array = array_type()
            for i in range(self.height):
                for j in range(self.width):
                    for k in range(4):
                        self.pixels_array[i][j][k] = pixels[i][j][k]
        pointer_type = ctypes.POINTER(ctypes.c_ubyte)
        self.pixels = ctypes.cast(self.pixels_array, pointer_type)
1180242
def display(self, image):
        
        assert(image.mode == self.mode)
        assert(image.size == self.size)

        image = self.preprocess(image)

        set_page_address = 0xB0

        image_data = image.getdata()
        pixels_per_page = self.width * 8
        buf = bytearray(self.width)

        for y in range(0, int(self._pages * pixels_per_page), pixels_per_page):
            self.command(set_page_address, 0x04, 0x10)
            set_page_address += 1
            offsets = [y + self.width * i for i in range(8)]

            for x in range(self.width):
                buf[x] = \
                    (image_data[x + offsets[0]] and 0x01) | \
                    (image_data[x + offsets[1]] and 0x02) | \
                    (image_data[x + offsets[2]] and 0x04) | \
                    (image_data[x + offsets[3]] and 0x08) | \
                    (image_data[x + offsets[4]] and 0x10) | \
                    (image_data[x + offsets[5]] and 0x20) | \
                    (image_data[x + offsets[6]] and 0x40) | \
                    (image_data[x + offsets[7]] and 0x80)

            self.data(list(buf))
1052028
def image(self):
        ''''''
        r = requests.get(self.image_url, stream=True)
        r.raise_for_status()
        return r.raw.read()
1282062
def image(self, image):
        
        if image.mode != '1':
            raise ValueError('Image must be in mode 1.')
        imwidth, imheight = image.size
        if imwidth != self.width or imheight != self.height:
            raise ValueError('Image must be same dimensions as display ({0}x{1}).' \
                .format(self.width, self.height))
        print("bitmap display: image")
        image.save("dummydisplay.bmp")
1176964
def prepare_image(self, image):
        
        from decaf.util import transform  # soft dep
        _JEFFNET_FLIP = True

        # first, extract the 256x256 center.
        image = transform.scale_and_extract(transform.as_rgb(image), 256)
        # convert to [0,255] float32
        image = image.astype(np.float32) * 255.
        if _JEFFNET_FLIP:
            # Flip the image if necessary, maintaining the c_contiguous order
            image = image[::-1, :].copy()
        # subtract the mean
        image -= self.net_._data_mean
        return image
726185
def _get_image_url(self, image_id):
        
        gce = self._connect()
        filter = "name eq %s" % image_id
        request = gce.images().list(project=self._project_id, filter=filter)
        response = self._execute_request(request)
        response = self._wait_until_done(response)

        image_url = None
        if "items" in response:
            image_url = response["items"][0]["selfLink"]

        if image_url:
            return image_url
        else:
            raise ImageError("Could not find given image id `%s`" % image_id)