Commits

Anonymous committed 2ca7416 Draft

rename to package

  • Participants
  • Parent commits f4386f8

Comments (0)

Files changed (2)

fakepil/__init__.py

+"""fakepil emulates VERY small portion of Image module from http://www.pythonware.com/products/pil/
+
+sample usage:
+
+try:
+    raise ImportError
+    import Image    # http://www.pythonware.com/products/pil/
+except ImportError:
+    import fakepil as Image
+
+Or:
+
+    Create PIL directory
+    Create empty __init__.py file
+    copy  fakepil.py PIL\Image.py  # Windows
+    cp  fakepil.py PIL/Image.py  # Unix
+
+Then in code:
+
+    # For import of (potentially fake) PIL so reportlab has what it needs
+
+    import PIL
+    from PIL import Image
+
+Has enough functionality for:
+ * kpg
+ * ReportLab 2.4
+To work.
+
+FIXME TODO error handling (test missing file in PIL)
+FIXME TODO add some del statements for objects we no longer need a reference to (to try and save memory)
+FIXME TODO also look at http://the.taoofmac.com/space/projects/PNGCanvas - has a different approach/API may be useful (check transparency support, etc.)
+FIXME TODO also add: http://code.google.com/p/pybmp
+look at http://pypi.python.org/pypi/ImageSize/
+not worth adding but interesting; http://www.ssokolow.com/scripts/?get=gif.py
+
+Very limited, barely enough to allow kpg to run. Allows snowflake.png and non-transparent gifs (like smiley_wink_14x9.gif) to run with kpg
+
+Limitations that impact kpg:
+
+ * png+gif only at the moment
+ * transparency support is non-existent, this may partly be due to png.py and pygif.py behavior (e.g. transparency attribute is not set correctly, nor bit plane depth)
+ * non-indexed files not handled gracefully, this may partly be due to png.py behavior (e.g. alpha, bit plane depth)
+"""
+
+import os
+
+try:
+    import png  # from http://code.google.com/p/pypng/
+except ImportError:
+    png = None
+try:
+    import pygif  # from http://emesene.svn.sourceforge.net/viewvc/emesene/trunk/emesene/pygif/
+except ImportError:
+    pygif = None
+
+
+class ImagePalette(object):
+    def __init__(self, pal_type, pal_data):
+        self.pal_type, self.pal_data = pal_type, pal_data
+        pass
+        
+    def getdata(self,):
+        return self.pal_type, self.pal_data
+
+    def _inded_getdata(self,):
+        ## not like Image returns in indexed format so no need for mygetpalette() code...
+        return self.pal_type, self.pal_data
+
+class Image(object):
+    def tostring(self):
+        width, height = self.size
+        result = []
+        for y in range(height):
+            for x in range(width):
+                pixel_info = self.getpixel((x, y))
+                if self.mode == 'P':
+                    #print repr(pixel_info)
+                    result.append(chr(pixel_info))
+                elif self.mode == 'RGB':
+                    result.append(chr(pixel_info[0])+chr(pixel_info[1])+chr(pixel_info[2]))
+        return ''.join(result)
+    
+    def convert(self, the_mode):
+        """WARNING convert is not really implemented:
+            1) expects to be used thusly; im = im.convert('RGB')  # i.e. do not use original
+            2) does nothing other than change the reported mode
+            3) only supports mode of RGB.
+        
+        This is all that is needed to fake our ReportLab version 2.4
+        """
+        assert the_mode == 'RGB'
+        self.mode = 'RGB'
+        return self
+    
+    def getpixel(self, xy_tuple):
+        tmp_pixel_info = self._getpixel_P(xy_tuple)
+        if self.mode == 'P':
+            return tmp_pixel_info
+        elif self.mode == 'RGB':
+            return self._usable_palette[tmp_pixel_info]
+
+
+class PngImageFile(Image):
+    def __init__(self, filename=None, fileobj=None):
+        if png is None:
+            raise ImportError('png module not available, obtain from http://code.google.com/p/pypng/')
+        self.info = {}
+        
+        if filename is None:
+            self.png_file = png.Reader(file=fileobj)
+        else:
+            self.png_file = png.Reader(filename=filename)
+        #self.png_file = png.Reader(filename=filename)
+        
+        
+        # Pick one and only one!
+        #width, height, pixels, meta = self.png_file.asDirect()
+        #width, height, pixels, meta = self.png_file.read()  # `pixels` are returned in boxed row flat pixel format.
+        #width, height, pixels, self._meta = self.png_file.read()
+        #print 'read meta info: width, height, self._meta', filename, width, height, self._meta['alpha']
+        #print 'read info: width, height, self._meta', filename, width, height, self._meta
+        try:
+            width, height, pixels, self._meta = self.png_file.asRGB()
+        except png.FormatError, error_info:
+            raise IOError(str(error_info))
+        #print 'RGB info: width, height, self._meta', filename, width, height, self._meta
+        self.size = width, height
+        try:
+            self._usable_palette = self.png_file.palette()
+        except png.FormatError:
+            """probably not an indexed image so probably getting
+            FormatError: FormatError: Required PLTE chunk is missing in colour type 3 image.
+            """
+            # not really good PIL emu but enough for kpg to know this is not indexed (kpg checks for palette info)
+            self.palette =None
+            return
+        
+        """
+        self.png_file.transparent  # does not appear to have useful information at this point (may need to make further calls?)
+        print 'transparent', filename, self.png_file.transparent
+        if self.png_file.transparent is None:
+            # TODO test
+            self.info['transparency'] = 0
+        else:
+            # TODO test
+            self.info['transparency'] = 1
+        """
+        tmp_palette =[]
+        for x in self._usable_palette:
+            r, g, b = x  ## sanity check, assert length ==3
+            tmp_x = map(chr, x)
+            tmp_palette.append(''.join(tmp_x))
+        tmp_palette_str = ''.join(tmp_palette)
+        self.palette = ImagePalette('RGB', tmp_palette_str)
+        self.mode = 'P'
+        
+        self._reverse_palette = {}
+        #print 'palette', palette
+        for x, y in enumerate(self._usable_palette):
+            #print 'xy', x, y
+            self._reverse_palette[y] = x
+        
+        self._indexed_pixels = []
+        for row in pixels:
+            row_of_pixels = []
+            while row:
+                r = row.pop(0)
+                g = row.pop(0)
+                b = row.pop(0)
+                index_pos = self._reverse_palette[(r, g, b)]
+                row_of_pixels.append(index_pos)
+            self._indexed_pixels.append(row_of_pixels)
+    
+    def _getpixel_P(self, xy_tuple):
+        (x, y) = xy_tuple
+        return self._indexed_pixels[y][x]  # note y, x versus x, y 
+
+
+class GifImageFile(Image):
+    def __init__(self, filename=None, fileobj=None):
+        if pygif is None:
+            raise ImportError('pygif module not available, obtain from http://emesene.svn.sourceforge.net/viewvc/emesene/trunk/emesene/pygif/')
+
+        if filename:
+            giffile = builtins_open(filename, 'rb')  # open is overridden to emulate Image module
+            gifdata = giffile.read()
+            giffile.close()
+        elif fileobj:
+            gifdata = fileobj.read()
+
+        try:
+            self._gif = pygif.GifDecoder(gifdata)
+        except IndexError:
+            # pygif does not appear to handle transparent GIFs
+            raise IOError('Error loading GIF. Transparent GIFs are not supported.')
+            #raise NotImplemented('Error loading GIF. suspect we have a transparent GIF')
+        # 'header', 'ls_width', 'ls_height', 'background_color', 'color_resolution', 'global_color_table_size', 'color_table_flag', 'pallete'
+        
+        self.size = self._gif.ls_width, self._gif.ls_height
+        self._usable_palette = self._gif.pallete
+        self._indexed_pixels = self._gif.images[0].pixels  # take the first image
+        
+        self.info = {}
+        
+        tmp_palette =[]
+        for x in self._usable_palette:
+            r, g, b = x  ## sanity check, assert length ==3
+            tmp_x = map(chr, x)
+            tmp_palette.append(''.join(tmp_x))
+        tmp_palette_str = ''.join(tmp_palette)
+        self.palette = ImagePalette('RGB', tmp_palette_str)
+        self.mode = 'P'
+    
+    def _getpixel_P(self, xy_tuple):
+        (x, y) = xy_tuple
+        
+        tmp_index = y * self._gif.ls_width + x
+        tmp_pixel_info = self._indexed_pixels[tmp_index]
+        """
+        if self.mode == 'P':
+            return tmp_pixel_info
+        elif self.mode == 'RGB':
+            return self._usable_palette[tmp_pixel_info]
+        """
+        return tmp_pixel_info
+
+
+
+"""
+class Image(object):
+    @classmethod
+    def open(cls, filename):
+        return PngImageFile(filename)
+"""
+
+
+VERSION = '1.1.7'  # what we would want if we emulate latest PIL as of June 2010
+VERSION = '0.0.1'  # don't lie about the version until we need to
+
+builtins_open = open
+def open(filename):
+    """Emulate Image.open, if built in open/file is needed use: builtins_open, for some reason this over rides __builtins__.open()
+    """
+    types2image = {
+        '.png' : PngImageFile,
+        '.gif' : GifImageFile,
+        }
+    
+    """
+    print type(filename)
+    print dir(filename)
+    print hasattr(filename, 'read')
+    if hasattr(filename, 'read'):
+        # filename isn't a filename, it is a file object
+    # may have url like name (due to TRML)
+    if filename.startswith('file:'):
+        filename = filename[len('file:'):]
+    """
+    if hasattr(filename, 'read'):
+        # filename isn't a filename, it is a file object
+        #print dir(filename)
+        #image_basename = filename.fileName[len('file:'):]
+        ## dumb file type detection for fileobjects, want to get access to StringIO filename... (or sniff first few bytes)
+        sniff_bytes = filename.read(5)
+        #print 'sniff_bytes', repr(sniff_bytes)
+        filename.seek(0)
+        if sniff_bytes.startswith('\x89PNG'):
+            image_basename = 'fakepil.png'
+        elif sniff_bytes.startswith('GIF'):
+            image_basename = 'fakepil.gif'
+    else:
+        image_basename = filename
+    image_basename = os.path.basename(image_basename)
+    file_extn = os.path.splitext(image_basename)[1]
+    file_extn = file_extn.lower()
+    image_class = types2image.get(file_extn, PngImageFile)
+    if hasattr(filename, 'read'):
+        #print 'has read', dir(filename)
+        #print 'call read', filename.read()
+        #print 'call getvalue', filename.getvalue()
+        return image_class(fileobj=filename)
+    return image_class(filename)

fakepil/fakepil.py

-"""fakepil emulates VERY small portion of Image module from http://www.pythonware.com/products/pil/
-
-sample usage:
-
-try:
-    raise ImportError
-    import Image    # http://www.pythonware.com/products/pil/
-except ImportError:
-    import fakepil as Image
-
-Or:
-
-    Create PIL directory
-    Create empty __init__.py file
-    copy  fakepil.py PIL\Image.py  # Windows
-    cp  fakepil.py PIL/Image.py  # Unix
-
-Then in code:
-
-    # For import of (potentially fake) PIL so reportlab has what it needs
-
-    import PIL
-    from PIL import Image
-
-Has enough functionality for:
- * kpg
- * ReportLab 2.4
-To work.
-
-FIXME TODO error handling (test missing file in PIL)
-FIXME TODO add some del statements for objects we no longer need a reference to (to try and save memory)
-FIXME TODO also look at http://the.taoofmac.com/space/projects/PNGCanvas - has a different approach/API may be useful (check transparency support, etc.)
-FIXME TODO also add: http://code.google.com/p/pybmp
-look at http://pypi.python.org/pypi/ImageSize/
-not worth adding but interesting; http://www.ssokolow.com/scripts/?get=gif.py
-
-Very limited, barely enough to allow kpg to run. Allows snowflake.png and non-transparent gifs (like smiley_wink_14x9.gif) to run with kpg
-
-Limitations that impact kpg:
-
- * png+gif only at the moment
- * transparency support is non-existent, this may partly be due to png.py and pygif.py behavior (e.g. transparency attribute is not set correctly, nor bit plane depth)
- * non-indexed files not handled gracefully, this may partly be due to png.py behavior (e.g. alpha, bit plane depth)
-"""
-
-import os
-
-try:
-    import png  # from http://code.google.com/p/pypng/
-except ImportError:
-    png = None
-try:
-    import pygif  # from http://emesene.svn.sourceforge.net/viewvc/emesene/trunk/emesene/pygif/
-except ImportError:
-    pygif = None
-
-
-class ImagePalette(object):
-    def __init__(self, pal_type, pal_data):
-        self.pal_type, self.pal_data = pal_type, pal_data
-        pass
-        
-    def getdata(self,):
-        return self.pal_type, self.pal_data
-
-    def _inded_getdata(self,):
-        ## not like Image returns in indexed format so no need for mygetpalette() code...
-        return self.pal_type, self.pal_data
-
-class Image(object):
-    def tostring(self):
-        width, height = self.size
-        result = []
-        for y in range(height):
-            for x in range(width):
-                pixel_info = self.getpixel((x, y))
-                if self.mode == 'P':
-                    #print repr(pixel_info)
-                    result.append(chr(pixel_info))
-                elif self.mode == 'RGB':
-                    result.append(chr(pixel_info[0])+chr(pixel_info[1])+chr(pixel_info[2]))
-        return ''.join(result)
-    
-    def convert(self, the_mode):
-        """WARNING convert is not really implemented:
-            1) expects to be used thusly; im = im.convert('RGB')  # i.e. do not use original
-            2) does nothing other than change the reported mode
-            3) only supports mode of RGB.
-        
-        This is all that is needed to fake our ReportLab version 2.4
-        """
-        assert the_mode == 'RGB'
-        self.mode = 'RGB'
-        return self
-    
-    def getpixel(self, xy_tuple):
-        tmp_pixel_info = self._getpixel_P(xy_tuple)
-        if self.mode == 'P':
-            return tmp_pixel_info
-        elif self.mode == 'RGB':
-            return self._usable_palette[tmp_pixel_info]
-
-
-class PngImageFile(Image):
-    def __init__(self, filename=None, fileobj=None):
-        if png is None:
-            raise ImportError('png module not available, obtain from http://code.google.com/p/pypng/')
-        self.info = {}
-        
-        if filename is None:
-            self.png_file = png.Reader(file=fileobj)
-        else:
-            self.png_file = png.Reader(filename=filename)
-        #self.png_file = png.Reader(filename=filename)
-        
-        
-        # Pick one and only one!
-        #width, height, pixels, meta = self.png_file.asDirect()
-        #width, height, pixels, meta = self.png_file.read()  # `pixels` are returned in boxed row flat pixel format.
-        #width, height, pixels, self._meta = self.png_file.read()
-        #print 'read meta info: width, height, self._meta', filename, width, height, self._meta['alpha']
-        #print 'read info: width, height, self._meta', filename, width, height, self._meta
-        try:
-            width, height, pixels, self._meta = self.png_file.asRGB()
-        except png.FormatError, error_info:
-            raise IOError(str(error_info))
-        #print 'RGB info: width, height, self._meta', filename, width, height, self._meta
-        self.size = width, height
-        try:
-            self._usable_palette = self.png_file.palette()
-        except png.FormatError:
-            """probably not an indexed image so probably getting
-            FormatError: FormatError: Required PLTE chunk is missing in colour type 3 image.
-            """
-            # not really good PIL emu but enough for kpg to know this is not indexed (kpg checks for palette info)
-            self.palette =None
-            return
-        
-        """
-        self.png_file.transparent  # does not appear to have useful information at this point (may need to make further calls?)
-        print 'transparent', filename, self.png_file.transparent
-        if self.png_file.transparent is None:
-            # TODO test
-            self.info['transparency'] = 0
-        else:
-            # TODO test
-            self.info['transparency'] = 1
-        """
-        tmp_palette =[]
-        for x in self._usable_palette:
-            r, g, b = x  ## sanity check, assert length ==3
-            tmp_x = map(chr, x)
-            tmp_palette.append(''.join(tmp_x))
-        tmp_palette_str = ''.join(tmp_palette)
-        self.palette = ImagePalette('RGB', tmp_palette_str)
-        self.mode = 'P'
-        
-        self._reverse_palette = {}
-        #print 'palette', palette
-        for x, y in enumerate(self._usable_palette):
-            #print 'xy', x, y
-            self._reverse_palette[y] = x
-        
-        self._indexed_pixels = []
-        for row in pixels:
-            row_of_pixels = []
-            while row:
-                r = row.pop(0)
-                g = row.pop(0)
-                b = row.pop(0)
-                index_pos = self._reverse_palette[(r, g, b)]
-                row_of_pixels.append(index_pos)
-            self._indexed_pixels.append(row_of_pixels)
-    
-    def _getpixel_P(self, xy_tuple):
-        (x, y) = xy_tuple
-        return self._indexed_pixels[y][x]  # note y, x versus x, y 
-
-
-class GifImageFile(Image):
-    def __init__(self, filename=None, fileobj=None):
-        if pygif is None:
-            raise ImportError('pygif module not available, obtain from http://emesene.svn.sourceforge.net/viewvc/emesene/trunk/emesene/pygif/')
-
-        if filename:
-            giffile = builtins_open(filename, 'rb')  # open is overridden to emulate Image module
-            gifdata = giffile.read()
-            giffile.close()
-        elif fileobj:
-            gifdata = fileobj.read()
-
-        try:
-            self._gif = pygif.GifDecoder(gifdata)
-        except IndexError:
-            # pygif does not appear to handle transparent GIFs
-            raise IOError('Error loading GIF. Transparent GIFs are not supported.')
-            #raise NotImplemented('Error loading GIF. suspect we have a transparent GIF')
-        # 'header', 'ls_width', 'ls_height', 'background_color', 'color_resolution', 'global_color_table_size', 'color_table_flag', 'pallete'
-        
-        self.size = self._gif.ls_width, self._gif.ls_height
-        self._usable_palette = self._gif.pallete
-        self._indexed_pixels = self._gif.images[0].pixels  # take the first image
-        
-        self.info = {}
-        
-        tmp_palette =[]
-        for x in self._usable_palette:
-            r, g, b = x  ## sanity check, assert length ==3
-            tmp_x = map(chr, x)
-            tmp_palette.append(''.join(tmp_x))
-        tmp_palette_str = ''.join(tmp_palette)
-        self.palette = ImagePalette('RGB', tmp_palette_str)
-        self.mode = 'P'
-    
-    def _getpixel_P(self, xy_tuple):
-        (x, y) = xy_tuple
-        
-        tmp_index = y * self._gif.ls_width + x
-        tmp_pixel_info = self._indexed_pixels[tmp_index]
-        """
-        if self.mode == 'P':
-            return tmp_pixel_info
-        elif self.mode == 'RGB':
-            return self._usable_palette[tmp_pixel_info]
-        """
-        return tmp_pixel_info
-
-
-
-"""
-class Image(object):
-    @classmethod
-    def open(cls, filename):
-        return PngImageFile(filename)
-"""
-
-
-VERSION = '1.1.7'  # what we would want if we emulate latest PIL as of June 2010
-VERSION = '0.0.1'  # don't lie about the version until we need to
-
-builtins_open = open
-def open(filename):
-    """Emulate Image.open, if built in open/file is needed use: builtins_open, for some reason this over rides __builtins__.open()
-    """
-    types2image = {
-        '.png' : PngImageFile,
-        '.gif' : GifImageFile,
-        }
-    
-    """
-    print type(filename)
-    print dir(filename)
-    print hasattr(filename, 'read')
-    if hasattr(filename, 'read'):
-        # filename isn't a filename, it is a file object
-    # may have url like name (due to TRML)
-    if filename.startswith('file:'):
-        filename = filename[len('file:'):]
-    """
-    if hasattr(filename, 'read'):
-        # filename isn't a filename, it is a file object
-        #print dir(filename)
-        #image_basename = filename.fileName[len('file:'):]
-        ## dumb file type detection for fileobjects, want to get access to StringIO filename... (or sniff first few bytes)
-        sniff_bytes = filename.read(5)
-        #print 'sniff_bytes', repr(sniff_bytes)
-        filename.seek(0)
-        if sniff_bytes.startswith('\x89PNG'):
-            image_basename = 'fakepil.png'
-        elif sniff_bytes.startswith('GIF'):
-            image_basename = 'fakepil.gif'
-    else:
-        image_basename = filename
-    image_basename = os.path.basename(image_basename)
-    file_extn = os.path.splitext(image_basename)[1]
-    file_extn = file_extn.lower()
-    image_class = types2image.get(file_extn, PngImageFile)
-    if hasattr(filename, 'read'):
-        #print 'has read', dir(filename)
-        #print 'call read', filename.read()
-        #print 'call getvalue', filename.getvalue()
-        return image_class(fileobj=filename)
-    return image_class(filename)