Example #1
0
    def save(self, filename, file_format=None):
        """ Save the contents of the context to a file
        """
        try:
            from kiva.compat import pilfromstring
        except ImportError:
            raise ImportError("need PIL (or Pillow) to save images")

        if file_format is None:
            file_format = ''

        # Data is BGRA; Convert to RGBA
        pixels = self.gc.array
        data = np.empty(pixels.shape, dtype=np.uint8)
        data[..., 0] = pixels[..., 2]
        data[..., 1] = pixels[..., 1]
        data[..., 2] = pixels[..., 0]
        data[..., 3] = pixels[..., 3]
        size = (int(self._width), int(self._height))
        img = pilfromstring('RGBA', size, data)

        # Check the output format to see if it can handle an alpha channel.
        no_alpha_formats = ('jpg', 'bmp', 'eps', 'jpeg')
        if ((isinstance(filename, str)
             and os.path.splitext(filename)[1][1:] in no_alpha_formats)
                or (file_format.lower() in no_alpha_formats)):
            img = img.convert('RGB')

        img.save(filename, format=file_format)
Example #2
0
    def save(self, filename, file_format=None):
        """ Save the contents of the context to a file
        """
        try:
            from kiva.compat import pilfromstring
        except ImportError:
            raise ImportError("need PIL (or Pillow) to save images")

        if file_format is None:
            file_format = ''

        # Data is BGRA; Convert to RGBA
        pixels = self.gc.array
        data = np.empty(pixels.shape, dtype=np.uint8)
        data[..., 0] = pixels[..., 2]
        data[..., 1] = pixels[..., 1]
        data[..., 2] = pixels[..., 0]
        data[..., 3] = pixels[..., 3]
        size = (int(self._width), int(self._height))
        img = pilfromstring('RGBA', size, data)

        # Check the output format to see if it can handle an alpha channel.
        no_alpha_formats = ('jpg', 'bmp', 'eps', 'jpeg')
        if ((isinstance(filename, str) and
                os.path.splitext(filename)[1][1:] in no_alpha_formats) or
                (file_format.lower() in no_alpha_formats)):
            img = img.convert('RGB')

        img.save(filename, format=file_format)
Example #3
0
    def draw_image(self, img, rect=None):
        """
        draw_image(img_gc, rect=(x, y, w, h))

        Draws another gc into this one.  If 'rect' is not provided, then
        the image gc is drawn into this one, rooted at (0, 0) and at full
        pixel size.  If 'rect' is provided, then the image is resized
        into the (w, h) given and drawn into this GC at point (x, y).

        img_gc is either a Numeric array (WxHx3 or WxHx4) or a GC from Kiva's
        Agg backend (kiva.agg.GraphicsContextArray).

        Requires the Python Imaging Library (PIL).
        """

        # We turn img into a PIL object, since that is what ReportLab
        # requires.  To do this, we first determine if the input image
        # GC needs to be converted to RGBA/RGB.  If so, we see if we can
        # do it nicely (using convert_pixel_format), and if not, we do
        # it brute-force using Agg.
        from reportlab.lib.utils import ImageReader
        from kiva import agg
        from kiva.compat import pilfromstring, piltostring

        if type(img) == type(array([])):
            # Numeric array
            converted_img = agg.GraphicsContextArray(img, pix_format='rgba32')
            format = 'RGBA'
        elif isinstance(img, agg.GraphicsContextArray):
            if img.format().startswith('RGBA'):
                format = 'RGBA'
            elif img.format().startswith('RGB'):
                format = 'RGB'
            else:
                converted_img = img.convert_pixel_format('rgba32', inplace=0)
                format = 'RGBA'
        else:
            warnings.warn("Cannot render image of type %r into PDF context."
                          % type(img))
            return

        # converted_img now holds an Agg graphics context with the image
        pil_img = pilfromstring(format,
                                (converted_img.width(),
                                 converted_img.height()),
                                piltostring(converted_img.bmp_array))

        if rect is None:
            rect = (0, 0, img.width(), img.height())

        # Draw the actual image.
        # Wrap it in an ImageReader object, because that's what reportlab
        # actually needs.
        self.gc.drawImage(ImageReader(pil_img),
                          rect[0], rect[1], rect[2], rect[3])
Example #4
0
    def draw_image(self, img, rect=None):
        """
        draw_image(img_gc, rect=(x, y, w, h))

        Draws another gc into this one.  If 'rect' is not provided, then
        the image gc is drawn into this one, rooted at (0, 0) and at full
        pixel size.  If 'rect' is provided, then the image is resized
        into the (w, h) given and drawn into this GC at point (x, y).

        img_gc is either a Numeric array (WxHx3 or WxHx4) or a GC from Kiva's
        Agg backend (kiva.agg.GraphicsContextArray).

        Requires the Python Imaging Library (PIL).
        """

        # We turn img into a PIL object, since that is what ReportLab
        # requires.  To do this, we first determine if the input image
        # GC needs to be converted to RGBA/RGB.  If so, we see if we can
        # do it nicely (using convert_pixel_format), and if not, we do
        # it brute-force using Agg.
        from reportlab.lib.utils import ImageReader
        from kiva import agg
        from kiva.compat import pilfromstring, piltostring

        if type(img) == type(array([])):
            # Numeric array
            converted_img = agg.GraphicsContextArray(img, pix_format='rgba32')
            format = 'RGBA'
        elif isinstance(img, agg.GraphicsContextArray):
            if img.format().startswith('RGBA'):
                format = 'RGBA'
            elif img.format().startswith('RGB'):
                format = 'RGB'
            else:
                converted_img = img.convert_pixel_format('rgba32', inplace=0)
                format = 'RGBA'
        else:
            warnings.warn("Cannot render image of type %r into PDF context."
                          % type(img))
            return

        # converted_img now holds an Agg graphics context with the image
        pil_img = pilfromstring(format,
                                (converted_img.width(),
                                 converted_img.height()),
                                piltostring(converted_img.bmp_array))

        if rect is None:
            rect = (0, 0, img.width(), img.height())

        # Draw the actual image.
        # Wrap it in an ImageReader object, because that's what reportlab
        # actually needs.
        self.gc.drawImage(ImageReader(pil_img),
                          rect[0], rect[1], rect[2], rect[3])
Example #5
0
def save(img, file_name):
    """ This only saves the rgb channels of the image
    """
    format = img.format()
    if format == "bgra32":
        size = (img.bmp_array.shape[1], img.bmp_array.shape[0])
        bgr = img.bmp_array[:, :, :3]
        rgb = bgr[:, :, ::-1].copy()
        st = rgb.tostring()
        pil_img = pilfromstring("RGB", size, st)
        pil_img.save(file_name)
    else:
        raise NotImplementedError("currently only supports writing out bgra32 images")
Example #6
0
def save(img, file_name):
    """ This only saves the rgb channels of the image
    """
    format = img.format()
    if format == "bgra32":
        size = (img.bmp_array.shape[1], img.bmp_array.shape[0])
        bgr = img.bmp_array[:, :, :3]
        rgb = bgr[:, :, ::-1].copy()
        st = rgb.tostring()
        pil_img = pilfromstring("RGB", size, st)
        pil_img.save(file_name)
    else:
        raise NotImplementedError(
            "currently only supports writing out bgra32 images")
Example #7
0
    def device_draw_image(self, img, rect):
        """
        draw_image(img_gc, rect=(x,y,w,h))

        Draws another gc into this one.  If 'rect' is not provided, then
        the image gc is drawn into this one, rooted at (0,0) and at full
        pixel size.  If 'rect' is provided, then the image is resized
        into the (w,h) given and drawn into this GC at point (x,y).

        img_gc is either a Numeric array (WxHx3 or WxHx4) or a GC from Kiva's
        Agg backend (kiva.agg.GraphicsContextArray).

        Requires the Python Imaging Library (PIL).
        """
        from kiva.compat import pilfromstring, piltostring, Image as PilImage

        # We turn img into a PIL object, since that is what ReportLab
        # requires.  To do this, we first determine if the input image
        # GC needs to be converted to RGBA/RGB.  If so, we see if we can
        # do it nicely (using convert_pixel_format), and if not, we do
        # it brute-force using Agg.


        if type(img) == type(array([])):
            # Numeric array
            converted_img = agg.GraphicsContextArray(img, pix_format='rgba32')
            format = 'RGBA'
        elif isinstance(img, agg.GraphicsContextArray):
            if img.format().startswith('RGBA'):
                format = 'RGBA'
            elif img.format().startswith('RGB'):
                format = 'RGB'
            else:
                converted_img = img.convert_pixel_format('rgba32', inplace=0)
                format = 'RGBA'
            # Should probably take this into account
            # interp = img.get_image_interpolation()
        else:
            warnings.warn("Cannot render image of type %r into SVG context."
                          % type(img))
            return

        # converted_img now holds an Agg graphics context with the image
        pil_img = pilfromstring(format,
                                (converted_img.width(),
                                 converted_img.height()),
                                piltostring(converted_img.bmp_array))
        if rect == None:
            rect = (0, 0, img.width(), img.height())

        left, top, width, height = rect
        if width != img.width() or height != img.height():
            # This is not strictly required.
            pil_img = pil_img.resize((int(width), int(height)), PilImage.NEAREST)

        png_buffer = six.StringIO()
        pil_img.save(png_buffer, 'png')
        b64_img_data = b64encode(png_buffer.getvalue())
        png_buffer.close()

        # Draw the actual image.
        m = self.get_ctm()
        # Place the image on the page.
        # Using bottom instead of top here to account for the y-flip.
        m = affine.translate(m, left, height + top)
        transform = 'matrix(%f,%f,%f,%f,%f,%f) scale(1,-1)' % affine.affine_params(m)
        # Flip y to reverse the flip at the start of the document.
        image_data = 'data:image/png;base64,' + b64_img_data
        self._emit('image', transform=transform,
                   width=str(width), height=str(height),
                   preserveAspectRatio='none',
                   kw={ 'xlink:href': image_data })
Example #8
0
    def device_draw_image(self, img, rect):
        """
        draw_image(img_gc, rect=(x,y,w,h))

        Draws another gc into this one.  If 'rect' is not provided, then
        the image gc is drawn into this one, rooted at (0,0) and at full
        pixel size.  If 'rect' is provided, then the image is resized
        into the (w,h) given and drawn into this GC at point (x,y).

        img_gc is either a Numeric array (WxHx3 or WxHx4) or a GC from Kiva's
        Agg backend (kiva.agg.GraphicsContextArray).

        Requires the Python Imaging Library (PIL).
        """
        from kiva.compat import pilfromstring, piltostring

        if type(img) == type(array([])):
            # Numeric array
            converted_img = agg.GraphicsContextArray(img, pix_format='rgba32')
            format = 'RGBA'
        elif isinstance(img, agg.GraphicsContextArray):
            if img.format().startswith('RGBA'):
                format = 'RGBA'
            elif img.format().startswith('RGB'):
                format = 'RGB'
            else:
                converted_img = img.convert_pixel_format('rgba32', inplace=0)
                format = 'RGBA'
            # Should probably take this into account
            # interp = img.get_image_interpolation()
        else:
            warnings.warn("Cannot render image of type %r into EPS context." %
                          type(img))
            return

        # converted_img now holds an Agg graphics context with the image
        pil_img = pilfromstring(
            format, (converted_img.width(), converted_img.height()),
            piltostring(converted_img.bmp_array))
        if rect is None:
            rect = (0, 0, img.width(), img.height())

        # PIL PS output doesn't support alpha.
        if format != 'RGB':
            pil_img = pil_img.convert('RGB')

        left, top, width, height = rect
        if width != img.width() or height != img.height():
            # This is not strictly required.
            pil_img = pil_img.resize((int(width), int(height)),
                                     PilImage.NEAREST)

        self.contents.write('gsave\n')
        self.contents.write('initmatrix\n')
        m = self.get_ctm()
        self.contents.write('[%.3f %.3f %.3f %.3f %.3f %.3f] concat\n' % \
                            affine.affine_params(m))
        self.contents.write('%.3f %.3f translate\n' % (left, top))
        # Rely on PIL's EpsImagePlugin to do the hard work here.
        pil_img.save(self.contents, 'eps', eps=0)
        self.contents.write('grestore\n')
Example #9
0
    def device_draw_image(self, img, rect):
        """
        draw_image(img_gc, rect=(x,y,w,h))

        Draws another gc into this one.  If 'rect' is not provided, then
        the image gc is drawn into this one, rooted at (0,0) and at full
        pixel size.  If 'rect' is provided, then the image is resized
        into the (w,h) given and drawn into this GC at point (x,y).

        img_gc is either a Numeric array (WxHx3 or WxHx4) or a GC from Kiva's
        Agg backend (kiva.agg.GraphicsContextArray).

        Requires the Python Imaging Library (PIL).
        """
        from kiva.compat import pilfromstring, piltostring

        if type(img) == type(array([])):
            # Numeric array
            converted_img = agg.GraphicsContextArray(img, pix_format='rgba32')
            format = 'RGBA'
        elif isinstance(img, agg.GraphicsContextArray):
            if img.format().startswith('RGBA'):
                format = 'RGBA'
            elif img.format().startswith('RGB'):
                format = 'RGB'
            else:
                converted_img = img.convert_pixel_format('rgba32', inplace=0)
                format = 'RGBA'
            # Should probably take this into account
            # interp = img.get_image_interpolation()
        else:
            warnings.warn("Cannot render image of type %r into EPS context."
                          % type(img))
            return

        # converted_img now holds an Agg graphics context with the image
        pil_img = pilfromstring(format,
                                (converted_img.width(),
                                 converted_img.height()),
                                piltostring(converted_img.bmp_array))
        if rect == None:
            rect = (0, 0, img.width(), img.height())

        # PIL PS output doesn't support alpha.
        if format != 'RGB':
            pil_img = pil_img.convert('RGB')

        left, top, width, height = rect
        if width != img.width() or height != img.height():
            # This is not strictly required.
            pil_img = pil_img.resize((int(width), int(height)), PilImage.NEAREST)

        self.contents.write('gsave\n')
        self.contents.write('initmatrix\n')
        m = self.get_ctm()
        self.contents.write('[%.3f %.3f %.3f %.3f %.3f %.3f] concat\n' % \
                            affine.affine_params(m))
        self.contents.write('%.3f %.3f translate\n' % (left, top))
        # Rely on PIL's EpsImagePlugin to do the hard work here.
        pil_img.save(self.contents, 'eps', eps=0)
        self.contents.write('grestore\n')
Example #10
0
    def device_draw_image(self, img, rect):
        """
        draw_image(img_gc, rect=(x,y,w,h))

        Draws another gc into this one.  If 'rect' is not provided, then
        the image gc is drawn into this one, rooted at (0,0) and at full
        pixel size.  If 'rect' is provided, then the image is resized
        into the (w,h) given and drawn into this GC at point (x,y).

        img_gc is either a Numeric array (WxHx3 or WxHx4) or a GC from Kiva's
        Agg backend (kiva.agg.GraphicsContextArray).

        Requires the Python Imaging Library (PIL).
        """
        from kiva.compat import pilfromstring, piltostring, Image as PilImage

        # We turn img into a PIL object, since that is what ReportLab
        # requires.  To do this, we first determine if the input image
        # GC needs to be converted to RGBA/RGB.  If so, we see if we can
        # do it nicely (using convert_pixel_format), and if not, we do
        # it brute-force using Agg.


        if type(img) == type(array([])):
            # Numeric array
            converted_img = agg.GraphicsContextArray(img, pix_format='rgba32')
            format = 'RGBA'
        elif isinstance(img, agg.GraphicsContextArray):
            if img.format().startswith('RGBA'):
                format = 'RGBA'
            elif img.format().startswith('RGB'):
                format = 'RGB'
            else:
                converted_img = img.convert_pixel_format('rgba32', inplace=0)
                format = 'RGBA'
            # Should probably take this into account
            # interp = img.get_image_interpolation()
        else:
            warnings.warn("Cannot render image of type %r into SVG context."
                          % type(img))
            return

        # converted_img now holds an Agg graphics context with the image
        pil_img = pilfromstring(format,
                                (converted_img.width(),
                                 converted_img.height()),
                                piltostring(converted_img.bmp_array))
        if rect == None:
            rect = (0, 0, img.width(), img.height())

        left, top, width, height = rect
        if width != img.width() or height != img.height():
            # This is not strictly required.
            pil_img = pil_img.resize((int(width), int(height)), PilImage.NEAREST)

        png_buffer = StringIO()
        pil_img.save(png_buffer, 'png')
        b64_img_data = b64encode(png_buffer.getvalue())
        png_buffer.close()

        # Draw the actual image.
        m = self.get_ctm()
        # Place the image on the page.
        # Using bottom instead of top here to account for the y-flip.
        m = affine.translate(m, left, height + top)
        transform = 'matrix(%f,%f,%f,%f,%f,%f) scale(1,-1)' % affine.affine_params(m)
        # Flip y to reverse the flip at the start of the document.
        image_data = 'data:image/png;base64,' + b64_img_data
        self._emit('image', transform=transform,
                   width=str(width), height=str(height),
                   preserveAspectRatio='none',
                   kw={ 'xlink:href': image_data })