Beispiel #1
0
def extract(filename, out_filename=None, preprocess=True, **kw):
    """
    :param filename: the input filename
    :param out_filename: output filename. if blank, will use temp files.
    """
    img = None
    extractor_class = None
    
    # some files need to have their contents checked before we can know whether or not we can
    # parse them. Preprocessing does that.
    if preprocess:
        for pp in PREPROCESSORS:
            if pp.preprocess(filename):
                extractor_class = pp
                break
    
    if not extractor_class:
        try:
            img = Image(filename)
        except:
            import sys
            print sys.exc_info()
            raise
        
        extractor_class = EXTRACTORS.get(img.format)
    
    if extractor_class:
        extractor = extractor_class(img, out_filename, filename)
        ext = extractor.extract(**kw)
        if img and hasattr(img, 'destroy'): img.destroy()
        return ext
    
    if img and hasattr(img, 'destroy'): img.destroy()
    raise Exception('Wrong format: %s' % img.format)
Beispiel #2
0
def thumbnail_wand(filename, size_x, distname):
	size = size_x, size_x
	from magickwand.image import Image
	im = Image(filename)
	if im.size > size:
		im.thumbnail(size_x)
	im.save(distname)
	del im
Beispiel #3
0
 def difference(cls, prev_image, current_image):
     """
     params are filenames
     """
     print 'diffing', prev_image, current_image
     
     f, name = cls._get_tmp_file(EXTRACT_TYPE_DIFF)
     
     print 'Saving diff to', name
     
     """
     # PIL -- This complains that some pairs of images 'do not match' Even when
     # they are generated from the same PSD and are the same pixel size. WTF.
     # USING IMAGEMAGICK INSTEAD, BITCHES
     p = PILImage.open(prev_image)
     c = PILImage.open(current_image)
     
     diff = ImageChops.difference(c, p)
     
     diff.save(f, cls.dest_format) #TODO catch IOError and do something with it.
     f.close()
     
     del p
     del c
     del diff
     """
     
     image = Image(current_image)
     other = Image(prev_image)
     
     isize = image.size
     osize = other.size
     
     offset = (0,0)
     if isize != osize:
         #enabling this makes the diff always the same size as the largest one
         #disabling makes it the size of the most current one. Hopefully this doesnt
         #happen very often...
         if False:#isize < osize: #basically, if both x and y components are less
             #swap; image is always the larger one
             tmp = image
             image = other
             other = tmp
             
             tmp = isize
             isize = osize
             osize = tmp
         
         offset = ((isize[0] - osize[0])/2, (isize[1] - osize[1])/2)
     
     image.composite(other, offset, operator=wand.DIFFERENCE_COMPOSITE_OP)
     
     f.write(image.dump(cls.dest_format))
     f.close()
     
     image.destroy()
     other.destroy()
     
     return ExtractedFile(name, EXTRACT_TYPE_DIFF)
Beispiel #4
0
def convert(source_fh, source_type, dest_type, dest_size):
    """somewhat like convert(1)"""
    i = Image(source_fh, source_type)

    if not i.select(dest_size):
        print "bad size"
        i.alpha(True)
        i.scale(dest_size)

    i.alpha(True)
    result = i.dump(dest_type)

    return result
Beispiel #5
0
def thumbnail_pil(filename, size_x, distname):
    size = size_x, size_x
    from PIL import Image
    im = Image.open(filename)
    if im.size > size:
        im.thumbnail(size, Image.ANTIALIAS)
    im.save(distname, im.format)
    del im
Beispiel #6
0
def thumbnail_pil(filename, size_x, distname):
	size = size_x, size_x
	from PIL import Image
	im = Image.open(filename)
	if im.size > size:
		im.thumbnail(size, Image.ANTIALIAS)
	im.save(distname, im.format)
	del im
Beispiel #7
0
def extract(filename, out_filename=None, preprocess=True, **kw):
    """
    :param filename: the input filename
    :param out_filename: output filename. if blank, will use temp files.
    """
    img = None
    extractor_class = None

    # some files need to have their contents checked before we can know whether or not we can
    # parse them. Preprocessing does that.
    if preprocess:
        for pp in PREPROCESSORS:
            if pp.preprocess(filename):
                extractor_class = pp
                break

    if not extractor_class:
        try:
            img = Image(filename)
        except:
            import sys
            print sys.exc_info()
            raise

        extractor_class = EXTRACTORS.get(img.format)

    if extractor_class:
        extractor = extractor_class(img, out_filename, filename)
        ext = extractor.extract(**kw)
        if img and hasattr(img, 'destroy'): img.destroy()
        return ext

    if img and hasattr(img, 'destroy'): img.destroy()
    raise Exception('Wrong format: %s' % img.format)
Beispiel #8
0
def thumbnail_wand(filename, size_x, distname):
    size = size_x, size_x
    from magickwand.image import Image
    im = Image(filename)
    if im.size > size:
        im.thumbnail(size_x)
    im.save(distname)
    del im
Beispiel #9
0
    def extract(self, async_extract=None, **kw):
        """
        Will return a list of all extracted files
        """
        if async_extract == True or (async_extract == None
                                     and ignore_fireworks()):
            return self.async_extract(**kw)

        parse_type = self.read_parse_type(self.filename)

        import os, os.path
        from mako.template import Template
        from mako.runtime import Context
        from StringIO import StringIO

        vol = urllib.quote(os.listdir('/Volumes')[0])
        prefix = 'file:///' + vol

        temp_dir = tempfile.mkdtemp()
        eid = 'FILE'

        data = {
            'in_file': prefix + os.path.abspath(self.filename),
            'out_dir': prefix + temp_dir + '/',
            'eid': eid
        }

        #script template
        here = os.path.dirname(os.path.dirname(__file__))
        script = os.path.join(here, 'backend', 'fireworks_export.js')
        mytemplate = Template(filename=script)
        buf = StringIO()
        ctx = Context(buf, **data)
        mytemplate.render_context(ctx)
        val = buf.getvalue()

        script, scname = self._get_tmp_file(None, dest_format='js')
        script.write(val)
        script.close()

        c = adobe.Fireworks()
        c.connect()

        error = None
        special_script = prefix + scname
        try:
            x = c.call('fw', 'runScript', special_script)
        except adobe.AdobeException as e:
            error = e
            if e.code != adobe.ERROR_DIED:
                raise
            print 'Fireworks died. But we kind of dont care. ON WITH IT, BITCHES.'

        os.remove(scname)

        regex = re.compile('FILE([0-9]+)')

        def key(s):
            m = regex.search(s)
            if m:
                return int(m.group(1))
            return None

        #now there should be files.
        files = os.listdir(temp_dir)
        files.sort(key=key)
        files = [
            ExtractedFile(os.path.join(temp_dir, f), EXTRACT_TYPE_FULL)
            for f in files if key(f) != None
        ]

        if files:
            self.image = Image(files[0].filename)
            files += self.thumbnail()
            self.image.destroy()
        elif error:
            raise error  #ok, maybe it legitimately died.

        return files, ExtractStatus(type=parse_type, file_type='FWPNG')
Beispiel #10
0
class FWPNGExtractor(Extractor):

    src_format = 'Unknown'
    dest_format = 'PNG'

    @classmethod
    def read_head(cls, filename):
        d = ''
        f = None
        try:
            f = open(filename, 'rb')
            d = f.read(500)
        finally:
            if f: f.close()
        return d

    @classmethod
    def read_parse_type(cls, filename):
        head = cls.read_head(filename)
        if 'Fireworks CS5' in head: return PARSE_TYPE_FIREWORKS_CS5
        elif 'Fireworks CS4' in head: return PARSE_TYPE_FIREWORKS_CS4
        elif 'Fireworks CS3' in head: return PARSE_TYPE_FIREWORKS_CS3
        elif 'Fireworks' in head: return PARSE_TYPE_FIREWORKS_OLD
        return PARSE_TYPE_UNKNOWN

    @classmethod
    def preprocess(cls, filename):

        head = cls.read_head(filename)

        isit = 'Fireworks' in head

        return isit

    def async_extract(self, **kw):

        parse_type = self.read_parse_type(self.filename)

        #this will parse with the simple png parser
        files, _ = extract(self.filename,
                           self.out_filename,
                           preprocess=False,
                           **kw)

        # let the external process know this needs to be parsed
        return files, ExtractStatus(PARSE_STATUS_PENDING,
                                    type=parse_type,
                                    file_type='FWPNG')

    def extract(self, async_extract=None, **kw):
        """
        Will return a list of all extracted files
        """
        if async_extract == True or (async_extract == None
                                     and ignore_fireworks()):
            return self.async_extract(**kw)

        parse_type = self.read_parse_type(self.filename)

        import os, os.path
        from mako.template import Template
        from mako.runtime import Context
        from StringIO import StringIO

        vol = urllib.quote(os.listdir('/Volumes')[0])
        prefix = 'file:///' + vol

        temp_dir = tempfile.mkdtemp()
        eid = 'FILE'

        data = {
            'in_file': prefix + os.path.abspath(self.filename),
            'out_dir': prefix + temp_dir + '/',
            'eid': eid
        }

        #script template
        here = os.path.dirname(os.path.dirname(__file__))
        script = os.path.join(here, 'backend', 'fireworks_export.js')
        mytemplate = Template(filename=script)
        buf = StringIO()
        ctx = Context(buf, **data)
        mytemplate.render_context(ctx)
        val = buf.getvalue()

        script, scname = self._get_tmp_file(None, dest_format='js')
        script.write(val)
        script.close()

        c = adobe.Fireworks()
        c.connect()

        error = None
        special_script = prefix + scname
        try:
            x = c.call('fw', 'runScript', special_script)
        except adobe.AdobeException as e:
            error = e
            if e.code != adobe.ERROR_DIED:
                raise
            print 'Fireworks died. But we kind of dont care. ON WITH IT, BITCHES.'

        os.remove(scname)

        regex = re.compile('FILE([0-9]+)')

        def key(s):
            m = regex.search(s)
            if m:
                return int(m.group(1))
            return None

        #now there should be files.
        files = os.listdir(temp_dir)
        files.sort(key=key)
        files = [
            ExtractedFile(os.path.join(temp_dir, f), EXTRACT_TYPE_FULL)
            for f in files if key(f) != None
        ]

        if files:
            self.image = Image(files[0].filename)
            files += self.thumbnail()
            self.image.destroy()
        elif error:
            raise error  #ok, maybe it legitimately died.

        return files, ExtractStatus(type=parse_type, file_type='FWPNG')
Beispiel #11
0
    def difference(cls, prev_image, current_image):
        """
        params are filenames
        """
        print 'diffing', prev_image, current_image

        f, name = cls._get_tmp_file(EXTRACT_TYPE_DIFF)

        print 'Saving diff to', name
        """
        # PIL -- This complains that some pairs of images 'do not match' Even when
        # they are generated from the same PSD and are the same pixel size. WTF.
        # USING IMAGEMAGICK INSTEAD, BITCHES
        p = PILImage.open(prev_image)
        c = PILImage.open(current_image)
        
        diff = ImageChops.difference(c, p)
        
        diff.save(f, cls.dest_format) #TODO catch IOError and do something with it.
        f.close()
        
        del p
        del c
        del diff
        """

        image = Image(current_image)
        other = Image(prev_image)

        isize = image.size
        osize = other.size

        offset = (0, 0)
        if isize != osize:
            #enabling this makes the diff always the same size as the largest one
            #disabling makes it the size of the most current one. Hopefully this doesnt
            #happen very often...
            if False:  #isize < osize: #basically, if both x and y components are less
                #swap; image is always the larger one
                tmp = image
                image = other
                other = tmp

                tmp = isize
                isize = osize
                osize = tmp

            offset = ((isize[0] - osize[0]) / 2, (isize[1] - osize[1]) / 2)

        image.composite(other, offset, operator=wand.DIFFERENCE_COMPOSITE_OP)

        f.write(image.dump(cls.dest_format))
        f.close()

        image.destroy()
        other.destroy()

        return ExtractedFile(name, EXTRACT_TYPE_DIFF)
Beispiel #12
0
def print_all_property():
    origin_img = Image('test.jpg')
    print origin_img.size
Beispiel #13
0
#!/usr/bin/env python

from magickwand.image import Image
import sys

if __name__=='__main__':
    img = Image(sys.argv[1])
    
    props = ['format', 'units', 'size', 'compression', 'background_color', 'colorspace']
    for p in props:
        print p, getattr(img, p)
    
    img.trim()
    print 'new size', img.size
    
    del img
Beispiel #14
0
 def extract(self, async_extract=None, **kw):
     """
     Will return a list of all extracted files
     """
     if async_extract == True or (async_extract == None and ignore_fireworks()):
         return self.async_extract(**kw)
     
     parse_type = self.read_parse_type(self.filename)
     
     import os, os.path
     from mako.template import Template
     from mako.runtime import Context
     from StringIO import StringIO
     
     vol = urllib.quote(os.listdir('/Volumes')[0])
     prefix = 'file:///'+ vol
     
     temp_dir = tempfile.mkdtemp()
     eid = 'FILE'
     
     data = {
         'in_file': prefix + os.path.abspath(self.filename),
         'out_dir': prefix + temp_dir + '/',
         'eid': eid
     }
     
     #script template
     here = os.path.dirname(os.path.dirname(__file__))
     script = os.path.join(here, 'backend', 'fireworks_export.js')
     mytemplate = Template(filename=script)
     buf = StringIO()
     ctx = Context(buf, **data)
     mytemplate.render_context(ctx)
     val = buf.getvalue()
     
     script, scname = self._get_tmp_file(None, dest_format='js')
     script.write(val)
     script.close()
     
     c = adobe.Fireworks()
     c.connect()
     
     error = None
     special_script = prefix + scname
     try:
         x = c.call('fw', 'runScript', special_script)
     except adobe.AdobeException as e:
         error = e
         if e.code != adobe.ERROR_DIED:
             raise
         print 'Fireworks died. But we kind of dont care. ON WITH IT, BITCHES.'
     
     os.remove(scname)
     
     regex = re.compile('FILE([0-9]+)')
     def key(s):
         m = regex.search(s)
         if m:
             return int(m.group(1))
         return None
     
     #now there should be files.
     files = os.listdir(temp_dir)
     files.sort(key=key)
     files = [ExtractedFile(os.path.join(temp_dir, f), EXTRACT_TYPE_FULL) for f in files if key(f) != None]
     
     if files:
         self.image = Image(files[0].filename)
         files += self.thumbnail()
         self.image.destroy()
     elif error:
         raise error #ok, maybe it legitimately died.
     
     return files, ExtractStatus(type=parse_type, file_type='FWPNG')
Beispiel #15
0
class FWPNGExtractor(Extractor):
    
    src_format = 'Unknown'
    dest_format = 'PNG'
    
    @classmethod
    def read_head(cls, filename):
        d = ''
        f = None
        try:
            f = open(filename, 'rb')
            d = f.read(500)
        finally:
            if f: f.close()
        return d
    
    @classmethod
    def read_parse_type(cls, filename):
        head = cls.read_head(filename)
        if 'Fireworks CS5' in head: return PARSE_TYPE_FIREWORKS_CS5
        elif 'Fireworks CS4' in head: return PARSE_TYPE_FIREWORKS_CS4
        elif 'Fireworks CS3' in head: return PARSE_TYPE_FIREWORKS_CS3
        elif 'Fireworks' in head: return PARSE_TYPE_FIREWORKS_OLD
        return PARSE_TYPE_UNKNOWN
    
    @classmethod
    def preprocess(cls, filename):
        
        head = cls.read_head(filename)
        
        isit = 'Fireworks' in head
        
        return isit
    
    def async_extract(self, **kw):
        
        parse_type = self.read_parse_type(self.filename)
        
        #this will parse with the simple png parser
        files, _ = extract(self.filename, self.out_filename, preprocess=False, **kw)
        
        # let the external process know this needs to be parsed
        return files, ExtractStatus(PARSE_STATUS_PENDING, type=parse_type, file_type='FWPNG')
        
    def extract(self, async_extract=None, **kw):
        """
        Will return a list of all extracted files
        """
        if async_extract == True or (async_extract == None and ignore_fireworks()):
            return self.async_extract(**kw)
        
        parse_type = self.read_parse_type(self.filename)
        
        import os, os.path
        from mako.template import Template
        from mako.runtime import Context
        from StringIO import StringIO
        
        vol = urllib.quote(os.listdir('/Volumes')[0])
        prefix = 'file:///'+ vol
        
        temp_dir = tempfile.mkdtemp()
        eid = 'FILE'
        
        data = {
            'in_file': prefix + os.path.abspath(self.filename),
            'out_dir': prefix + temp_dir + '/',
            'eid': eid
        }
        
        #script template
        here = os.path.dirname(os.path.dirname(__file__))
        script = os.path.join(here, 'backend', 'fireworks_export.js')
        mytemplate = Template(filename=script)
        buf = StringIO()
        ctx = Context(buf, **data)
        mytemplate.render_context(ctx)
        val = buf.getvalue()
        
        script, scname = self._get_tmp_file(None, dest_format='js')
        script.write(val)
        script.close()
        
        c = adobe.Fireworks()
        c.connect()
        
        error = None
        special_script = prefix + scname
        try:
            x = c.call('fw', 'runScript', special_script)
        except adobe.AdobeException as e:
            error = e
            if e.code != adobe.ERROR_DIED:
                raise
            print 'Fireworks died. But we kind of dont care. ON WITH IT, BITCHES.'
        
        os.remove(scname)
        
        regex = re.compile('FILE([0-9]+)')
        def key(s):
            m = regex.search(s)
            if m:
                return int(m.group(1))
            return None
        
        #now there should be files.
        files = os.listdir(temp_dir)
        files.sort(key=key)
        files = [ExtractedFile(os.path.join(temp_dir, f), EXTRACT_TYPE_FULL) for f in files if key(f) != None]
        
        if files:
            self.image = Image(files[0].filename)
            files += self.thumbnail()
            self.image.destroy()
        elif error:
            raise error #ok, maybe it legitimately died.
        
        return files, ExtractStatus(type=parse_type, file_type='FWPNG')