Convert an image to PNG format with Pillow.
	
	:arg file-like fp: The image file.
	:rtype: bytes
770076
def file_to_png(fp):
	
	import PIL.Image # pylint: disable=import-error
	with io.BytesIO() as dest:
		PIL.Image.open(fp).save(dest, "PNG", optimize=True)
		return dest.getvalue()
877476
def dump_img(fname):
    
    img = Image.open(fname)
    width, _ = img.size
    txt = ''
    pixels = list(img.getdata())
    for col in range(width):
        txt += str(pixels[col:col+width])
    return txt
1165558
def to_png(pdf_path):
  ''' 
  '''
  try:
    with NamedTemporaryFile(prefix='pyglass', suffix='.png', delete=False) as tempfileobj:
      png_path = tempfileobj.name

    cmd = ['sips', '-s', 'format', 'png', pdf_path, '--out', png_path]
    assert(check_call(cmd) == 0)

    assert(exists(png_path))
    return png_path
  except:
    return None
1307108
def toPIL(self, **attribs):
        
        import PIL.Image
        bytes = self.convert("png")
        sfile = io.BytesIO(bytes)
        pil = PIL.Image.open(sfile)
        return pil
24735
def draw_image(data, obj):
    
    content = []

    filename, rel_filepath = files.new_filename(data, "img", ".png")

    # store the image as in a file
    img_array = obj.get_array()

    dims = img_array.shape
    if len(dims) == 2:  # the values are given as one real number: look at cmap
        clims = obj.get_clim()
        mpl.pyplot.imsave(
            fname=filename,
            arr=img_array,
            cmap=obj.get_cmap(),
            vmin=clims[0],
            vmax=clims[1],
            origin=obj.origin,
        )
    else:
        # RGB (+alpha) information at each point
        assert len(dims) == 3 and dims[2] in [3, 4]
        # convert to PIL image
        if obj.origin == "lower":
            img_array = numpy.flipud(img_array)

        # Convert mpl image to PIL
        image = PIL.Image.fromarray(numpy.uint8(img_array * 255))

        # If the input image is PIL:
        # image = PIL.Image.fromarray(img_array)

        image.save(filename, origin=obj.origin)

    # write the corresponding information to the TikZ file
    extent = obj.get_extent()

    # the format specification will only accept tuples
    if not isinstance(extent, tuple):
        extent = tuple(extent)

    # Explicitly use \pgfimage as includegrapics command, as the default
    # \includegraphics fails unexpectedly in some cases
    ff = data["float format"]
    content.append(
        (
            "\\addplot graphics [includegraphics cmd=\\pgfimage,"
            "xmin=" + ff + ", xmax=" + ff + ", "
            "ymin=" + ff + ", ymax=" + ff + "] {{{}}};\n"
        ).format(*(extent + (rel_filepath,)))
    )

    return data, content
664128
def render_to_png(self, filename=None, dpi=72, **kwargs):
        """"""
        import cairosvg
        return cairosvg.svg2png(
            bytestring=self.render(**kwargs), write_to=filename, dpi=dpi
        )
442365
def convert_image(from_file, to_file, image_format):
    """"""
    with Image(filename=from_file) as original:
        with original.convert(image_format) as converted:
            converted.save(filename=to_file)
    return to_file
787211
def convert(f, opts = {})
      opts = opts.dup
      f = f.to_s.downcase
      allowed = %w(jpeg jpg png)
      raise ArgumentError, "Format must be one of: #{allowed.join(',')}" unless allowed.include?(f)
      self.format_override = f == 'jpeg' ? 'jpg' : f
      opts[:Q] = opts.delete(:quality) if opts.has_key?(:quality)
      write_opts.merge!(opts)
      get_image
    end
785489
def write_image_to_disk(self, msg, result, fh):
        """"""
        cairosvg.svg2png(bytestring=msg.encode('utf-8'), write_to=fh)
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)
121783
def to_pillow_image(self, return_mask=False):
        """"""
        img = np.rollaxis(np.rollaxis(self.image.data, 2), 2)
        img = Image.fromarray(img[:, :, 0]) if img.shape[2] == 1 else Image.fromarray(img)
        if return_mask:
            mask = np.ma.getmaskarray(self.image)
            mask = Image.fromarray(np.rollaxis(np.rollaxis(mask, 2), 2).astype(np.uint8)[:, :, 0])
            return img, mask
        else:
            return img
1068711
def parse_buffer_to_png(data):
    

    images = []

    c1 = 0
    c2 = 0
    data_len = len(data)
    while c1 < data_len:
        # IEND can appear in a PNG without being the actual end
        if data[c2:c2 + 4] == b'IEND' and (c2 + 8 == data_len or data[c2+9:c2+12] == b'PNG'):
            images.append(Image.open(BytesIO(data[c1:c2 + 8])))
            c1 = c2 + 8
            c2 = c1
        c2 += 1

    return images
1337025
def png(self):
        """"""
        use_plugin('freeimage')
        with TemporaryFilePath(suffix='.png') as tmp:
            safe_range_im = 255 * normalise(self)
            imsave(tmp.fpath, safe_range_im.astype(np.uint8))
            with open(tmp.fpath, 'rb') as fh:
                return fh.read()
526021
def plot(config, image, file):
    
    image = np.squeeze(image)
    print(file, image.shape)
    imsave(file, image)
361098
def _image_width(image):
    
    if not Image:
        raise Exception("Images manipulation require PIL")
    file = StringValue(image).value
    path = None
    try:
        width = sprite_images[file][0]
    except KeyError:
        width = 0
        if callable(STATIC_ROOT):
            try:
                _file, _storage = list(STATIC_ROOT(file))[0]
                path = _storage.open(_file)
            except:
                pass
        else:
            _path = os.path.join(STATIC_ROOT, file)
            if os.path.exists(_path):
                path = open(_path, 'rb')
        if path:
            image = Image.open(path)
            size = image.size
            width = size[0]
            sprite_images[file] = size
    return NumberValue(width, 'px')
678319
def as_pil_image(self):
        
        from PIL import Image

        try:
            bio = BytesIO()
            self._extract_direct(stream=bio)
            bio.seek(0)
            return Image.open(bio)
        except UnsupportedImageTypeError:
            pass

        im = self._extract_transcoded()
        if not im:
            raise UnsupportedImageTypeError(repr(self))

        return im
1135754
def _convert_image(self, im):
        
        pixels   = []
        pix_line = ""
        im_left  = ""
        im_right = ""
        switch   = 0
        img_size = [ 0, 0 ]


        if im.size[0] > 512:
            print  "WARNING: Image is wider than 512 and could be truncated at print time "
        if im.size[1] > 255:
            raise ImageSizeError()

        im_border = self._check_image_size(im.size[0])
        for i in range(im_border[0]):
            im_left += "0"
        for i in range(im_border[1]):
            im_right += "0"

        for y in range(im.size[1]):
            img_size[1] += 1
            pix_line += im_left
            img_size[0] += im_border[0]
            for x in range(im.size[0]):
                img_size[0] += 1
                RGB = im.getpixel((x, y))
                im_color = (RGB[0] + RGB[1] + RGB[2])
                im_pattern = "1X0"
                pattern_len = len(im_pattern)
                switch = (switch - 1 ) * (-1)
                for x in range(pattern_len):
                    if im_color <= (255 * 3 / pattern_len * (x+1)):
                        if im_pattern[x] == "X":
                            pix_line += "%d" % switch
                        else:
                            pix_line += im_pattern[x]
                        break
                    elif im_color > (255 * 3 / pattern_len * pattern_len) and im_color <= (255 * 3):
                        pix_line += im_pattern[-1]
                        break 
            pix_line += im_right
            img_size[0] += im_border[1]

        return (pix_line, img_size)