Example #1
0
def grabclipboard():
    if sys.platform == "darwin":
        fh, filepath = tempfile.mkstemp('.jpg')
        os.close(fh)
        commands = [
            "set theFile to (open for access POSIX file \"" + filepath +
            "\" with write permission)", "try",
            "write (the clipboard as JPEG picture) to theFile", "end try",
            "close access theFile"
        ]
        script = ["osascript"]
        for command in commands:
            script += ["-e", command]
        subprocess.call(script)

        im = None
        if os.stat(filepath).st_size != 0:
            im = Image.open(filepath)
            im.load()
        os.unlink(filepath)
        return im
    else:
        debug = 0  # temporary interface
        data = Image.core.grabclipboard(debug)
        if isinstance(data, bytes):
            from PIL import BmpImagePlugin
            import io
            return BmpImagePlugin.DibImageFile(io.BytesIO(data))
        return data
Example #2
0
def grabclipboard():
    debug = 0  # temporary interface
    data = Image.core.grabclipboard(debug)
    if isinstance(data, bytes):
        from PIL import BmpImagePlugin
        import io
        return BmpImagePlugin.DibImageFile(io.BytesIO(data))
    return data
Example #3
0
def grabclipboard():
    if sys.platform == "darwin":
        raise NotImplementedError("Method is not implemented on OS X")
    debug = 0  # temporary interface
    data = Image.core.grabclipboard(debug)
    if isinstance(data, bytes):
        from PIL import BmpImagePlugin
        import io
        return BmpImagePlugin.DibImageFile(io.BytesIO(data))
    return data
Example #4
0
 def test_truncated(self):
     b = BytesIO(
         b"BM000000000000"  # head_data
         + _binary.o32le(
             ImageFile.SAFEBLOCK + 1 + 4
         )  # header_size, so BmpImagePlugin will try to read SAFEBLOCK + 1 bytes
         + (b"0" * ImageFile.SAFEBLOCK
            )  # only SAFEBLOCK bytes, so that the header is truncated
     )
     with pytest.raises(OSError) as e:
         BmpImagePlugin.BmpImageFile(b)
     assert str(e.value) == "Truncated File Read"
Example #5
0
def _icon_chunk(header: Dict[str, Any], data: bytes, data_out: Dict[str, Any]):
    """
    Represents .ani icon chunk, which has an identifier of "icon".
    """
    if (header is None):
        raise SyntaxError("icon chunk became before header!")

    if (header["is_in_ico"]):
        # Cursors are stored as either .cur or .ico, use CurFormat to read them...
        cursor = CurFormat.read(BytesIO(data))
    else:
        # BMP format, load in and then correct the height...
        c_icon = CursorIcon(BmpImagePlugin.DibImageFile(BytesIO(data)), 0, 0)
        c_icon.image._size = (c_icon.image.size[0], c_icon.image.size[1] // 2)
        d, e, o, a = c_icon.image.tile[0]
        c_icon.image.tile[0] = d, (0, 0) + c_icon.image.size, o, a
        # Add the image to the cursor list...
        cursor = Cursor([c_icon])

    if ("list" not in data_out):
        data_out["list"] = []

    data_out["list"].append(cursor)
Example #6
0
    def frame(self, idx):
        """
        Get an image from frame idx
        """

        header = self.entry[idx]

        self.buf.seek(header['offset'])
        data = self.buf.read(8)
        self.buf.seek(header['offset'])

        if data[:8] == PngImagePlugin._MAGIC:
            # png frame
            im = PngImagePlugin.PngImageFile(self.buf)
        else:
            # XOR + AND mask bmp frame
            im = BmpImagePlugin.DibImageFile(self.buf)

            # change tile dimension to only encompass XOR image
            im.size = (im.size[0], int(im.size[1] / 2))
            d, e, o, a = im.tile[0]
            im.tile[0] = d, (0, 0) + im.size, o, a

            # figure out where AND mask image starts
            mode = a[0]
            bpp = 8
            for k in BmpImagePlugin.BIT2MODE.keys():
                if mode == BmpImagePlugin.BIT2MODE[k][1]:
                    bpp = k
                    break

            if 32 == bpp:
                # 32-bit color depth icon image allows semitransparent areas
                # PIL's DIB format ignores transparency bits, recover them.
                # The DIB is packed in BGRX byte order where X is the alpha
                # channel.

                # Back up to start of bmp data
                self.buf.seek(o)
                # extract every 4th byte (eg. 3,7,11,15,...)
                alpha_bytes = self.buf.read(im.size[0] * im.size[1] * 4)[3::4]

                # convert to an 8bpp grayscale image
                mask = Image.frombuffer(
                    'L',            # 8bpp
                    im.size,        # (w, h)
                    alpha_bytes,    # source chars
                    'raw',          # raw decoder
                    ('L', 0, -1)    # 8bpp inverted, unpadded, reversed
                )
            else:
                # get AND image from end of bitmap
                w = im.size[0]
                if (w % 32) > 0:
                    # bitmap row data is aligned to word boundaries
                    w += 32 - (im.size[0] % 32)

                # the total mask data is
                # padded row size * height / bits per char

                and_mask_offset = o + int(im.size[0] * im.size[1] *
                                          (bpp / 8.0))
                total_bytes = int((w * im.size[1]) / 8)

                self.buf.seek(and_mask_offset)
                mask_data = self.buf.read(total_bytes)

                # convert raw data to image
                mask = Image.frombuffer(
                    '1',            # 1 bpp
                    im.size,        # (w, h)
                    mask_data,      # source chars
                    'raw',          # raw decoder
                    ('1;I', int(w/8), -1)  # 1bpp inverted, padded, reversed
                )

                # now we have two images, im is XOR image and mask is AND image

            # apply mask image as alpha channel
            im = im.convert('RGBA')
            im.putalpha(mask)

        return im
Example #7
0
class IconImporter(object):

    def __init__(self, feed, page_data=None, force=False):
        self.feed = feed
        self.force = force
        self.page_data = page_data
        self.feed_icon = MFeedIcon.get_feed(feed_id=self.feed.pk)

    def save(self):
        if not self.force and self.feed.favicon_not_found:
            # print 'Not found, skipping...'
            return
        if (
                not self.force
                and not self.feed.favicon_not_found
                and self.feed_icon.icon_url
                and self.feed.s3_icon
        ):
            # print 'Found, but skipping...'
            return
        image, image_file, icon_url = self.fetch_image_from_page_data()
        if not image:
            image, image_file, icon_url = self.fetch_image_from_path(force=self.force)

        if image:
            image = self.normalize_image(image)
            try:
                color = self.determine_dominant_color_in_image(image)
            except IndexError:
                return
            try:
                image_str = self.string_from_image(image)
            except TypeError:
                return

            if len(image_str) > 500000:
                image = None
            if (image and
                (self.force or
                 self.feed_icon.data != image_str or
                 self.feed_icon.icon_url != icon_url or
                 self.feed_icon.not_found or
                 (settings.BACKED_BY_AWS.get('icons_on_s3') and not self.feed.s3_icon))):
                logging.debug(" ---> [%-30s] ~SN~FBIcon difference:~FY color:%s (%s/%s) data:%s url:%s notfound:%s no-s3:%s" % (
                    self.feed,
                    self.feed_icon.color != color, self.feed_icon.color, color,
                    self.feed_icon.data != image_str,
                    self.feed_icon.icon_url != icon_url,
                    self.feed_icon.not_found,
                    settings.BACKED_BY_AWS.get('icons_on_s3') and not self.feed.s3_icon))
                self.feed_icon.data = image_str
                self.feed_icon.icon_url = icon_url
                self.feed_icon.color = color
                self.feed_icon.not_found = False
                self.feed_icon.save()
                if settings.BACKED_BY_AWS.get('icons_on_s3'):
                    self.save_to_s3(image_str)
            if self.feed.favicon_color != color:
                self.feed.favicon_color = color
                self.feed.favicon_not_found = False
                self.feed.save(update_fields=['favicon_color', 'favicon_not_found'])

        if not image:
            self.feed_icon.not_found = True
            self.feed_icon.save()
            self.feed.favicon_not_found = True
            self.feed.save()
            
        return not self.feed.favicon_not_found

    def save_to_s3(self, image_str):
        expires = datetime.datetime.now() + datetime.timedelta(days=60)
        expires = expires.strftime("%a, %d %b %Y %H:%M:%S GMT")
        k = Key(settings.S3_ICONS_BUCKET)
        k.key = self.feed.s3_icons_key
        k.set_metadata('Content-Type', 'image/png')
        k.set_metadata('Expires', expires)
        k.set_contents_from_string(image_str.decode('base64'))
        k.set_acl('public-read')

        self.feed.s3_icon = True
        self.feed.save()

    def load_icon(self, image_file, index=None):
        '''
        DEPRECATED

        Load Windows ICO image.

        See http://en.wikipedia.org/w/index.php?oldid=264332061 for file format
        description.

        Cribbed and modified from http://djangosnippets.org/snippets/1287/
        '''
        try:
            image_file.seek(0)
            header = struct.unpack('<3H', image_file.read(6))
        except Exception, e:
            return

        # Check magic
        if header[:2] != (0, 1):
            return

        # Collect icon directories
        directories = []
        for i in xrange(header[2]):
            directory = list(struct.unpack('<4B2H2I', image_file.read(16)))
            for j in xrange(3):
                if not directory[j]:
                    directory[j] = 256

            directories.append(directory)

        if index is None:
            # Select best icon
            directory = max(directories, key=operator.itemgetter(slice(0, 3)))
        else:
            directory = directories[index]

        # Seek to the bitmap data
        image_file.seek(directory[7])

        prefix = image_file.read(16)
        image_file.seek(-16, 1)

        if PngImagePlugin._accept(prefix):
            # Windows Vista icon with PNG inside
            try:
                image = PngImagePlugin.PngImageFile(image_file)
            except IOError:
                return
        else:
            # Load XOR bitmap
            try:
                image = BmpImagePlugin.DibImageFile(image_file)
            except IOError:
                return
            if image.mode == 'RGBA':
                # Windows XP 32-bit color depth icon without AND bitmap
                pass
            else:
                # Patch up the bitmap height
                image.size = image.size[0], image.size[1] >> 1
                d, e, o, a = image.tile[0]
                image.tile[0] = d, (0, 0) + image.size, o, a

                # Calculate AND bitmap dimensions. See
                # http://en.wikipedia.org/w/index.php?oldid=264236948#Pixel_storage
                # for description
                offset = o + a[1] * image.size[1]
                stride = ((image.size[0] + 31) >> 5) << 2
                size = stride * image.size[1]

                # Load AND bitmap
                image_file.seek(offset)
                string = image_file.read(size)
                mask = Image.frombytes('1', image.size, string, 'raw',
                                       ('1;I', stride, -1))

                image = image.convert('RGBA')
                image.putalpha(mask)

        return image
Example #8
0
 def test_load_dib(self):
     # test for #1293, Imagegrab returning Unsupported Bitfields Format
     im = BmpImagePlugin.DibImageFile('Tests/images/clipboard.dib')
     target = Image.open('Tests/images/clipboard_target.png')
     self.assert_image_equal(im, target)
Example #9
0
 def test_invalid_file(self):
     with open("Tests/images/flower.jpg", "rb") as fp:
         self.assertRaises(SyntaxError,
                           lambda: BmpImagePlugin.BmpImageFile(fp))
Example #10
0
from cryptography.hazmat.backends import default_backend

backend = default_backend()

#Gerar chave aleatoria

key = os.urandom(32)
key

# initialization vector
iv = os.urandom(16)
iv

#Lendo e manipulando imagem de entrada em formato bmp:

input_image = BmpImagePlugin.BmpImageFile("teste.bmp")

image_data = input_image.tobytes()

# cifrando o dado com algoritmo AES no modo CBC:

# 1 - o objeto que criptografa AES com a chave gerada
aes = algorithms.AES(key)

# 2 - o  modo CBC em inicializaĆ§Ć£o
cbc = modes.CBC(iv)

# 3 - criando e encriptando a partir do cipher
cipher = Cipher(aes, cbc, backend=backend)
encryptor = cipher.encryptor()
ct = encryptor.update(image_data) + encryptor.finalize()
Example #11
0
def load_icon(_imgPath, index=None):
    if isinstance(_imgPath, basestring):
        file = open(_imgPath, 'rb')

    try:
        header = struct.unpack('<3H', file.read(6))
    except:
        raise IOError('Not an ICO file')

    # Check magic
    try:
        if header[:2] != (0, 1):
            raise IOError('Not an ICO file')
    except:
        return loadPNG(_imgPath)

    # Collect icon directories
    directories = []
    for i in xrange(header[2]):
        directory = list(struct.unpack('<4B2H2I', file.read(16)))
        for j in xrange(3):
            if not directory[j]:
                directory[j] = 256

        directories.append(directory)

    if index is None:
        # Select best icon
        directory = max(directories, key=operator.itemgetter(slice(0, 3)))
    else:
        directory = directories[index]

    # Seek to the bitmap data
    file.seek(directory[7])

    prefix = file.read(16)
    file.seek(-16, 1)

    if PngImagePlugin._accept(prefix):
        # Windows Vista icon with PNG inside
        image = PngImagePlugin.PngImageFile(file)
    else:
        # Load XOR bitmap
        image = BmpImagePlugin.DibImageFile(file)
        if image.mode == 'RGBA':
            # Windows XP 32-bit color depth icon without AND bitmap
            pass
        else:
            # Patch up the bitmap height
            image.size = image.size[0], image.size[1] >> 1
            d, e, o, a = image.tile[0]
            image.tile[0] = d, (0, 0) + image.size, o, a

            # Calculate AND bitmap dimensions. See
            offset = o + a[1] * image.size[1]
            stride = ((image.size[0] + 31) >> 5) << 2
            size = stride * image.size[1]

            # Load AND bitmap
            file.seek(offset)
            string = file.read(size)
            mask = Image.frombytes('1', image.size, string, 'raw',
                                   ('1;I', stride, -1))

            image = image.convert('RGBA')
            image.putalpha(mask)

    return image, image.size
Example #12
0
def test_invalid_file():
    with open("Tests/images/flower.jpg", "rb") as fp:
        with pytest.raises(SyntaxError):
            BmpImagePlugin.BmpImageFile(fp)
Example #13
0
def load_icon(file, index=None):
    '''
    Load Windows ICO image.

    See http://en.wikipedia.org/w/index.php?oldid=264332061 for file format
    description.
    '''
    if isinstance(file, basestring):
        file = open(file, 'rb')

    header = struct.unpack('<3H', file.read(6))

    # Check magic
    if header[:2] != (0, 1):
        raise SyntaxError('Not an ICO file')

    # Collect icon directories
    directories = []
    for i in xrange(header[2]):
        directory = list(struct.unpack('<4B2H2I', file.read(16)))
        for j in xrange(3):
            if not directory[j]:
                directory[j] = 256

        directories.append(directory)

    if index is None:
        # Select best icon
        directory = max(directories, key=operator.itemgetter(slice(0, 3)))
    else:
        directory = directories[index]

    # Seek to the bitmap data
    file.seek(directory[7])

    prefix = file.read(16)
    file.seek(-16, 1)

    if PngImagePlugin._accept(prefix):
        # Windows Vista icon with PNG inside
        image = PngImagePlugin.PngImageFile(file)
    else:
        # Load XOR bitmap
        image = BmpImagePlugin.DibImageFile(file)
        if image.mode == 'RGBA':
            # Windows XP 32-bit color depth icon without AND bitmap
            pass
        else:
            # Patch up the bitmap height
            image.size = image.size[0], image.size[1] >> 1
            d, e, o, a = image.tile[0]
            image.tile[0] = d, (0, 0) + image.size, o, a

            # Calculate AND bitmap dimensions. See
            # http://en.wikipedia.org/w/index.php?oldid=264236948#Pixel_storage
            # for description
            offset = o + a[1] * image.size[1]
            stride = ((image.size[0] + 31) >> 5) << 2
            size = stride * image.size[1]

            # Load AND bitmap
            file.seek(offset)
            string = file.read(size)
            mask = Image.fromstring('1', image.size, string, 'raw',
                                    ('1;I', stride, -1))

            image = image.convert('RGBA')
            image.putalpha(mask)

    return image
Example #14
0
        # Seek to the bitmap data
        image_file.seek(directory[7])

        prefix = image_file.read(16)
        image_file.seek(-16, 1)

        if PngImagePlugin._accept(prefix):
            # Windows Vista icon with PNG inside
            try:
                image = PngImagePlugin.PngImageFile(image_file)
            except IOError:
                return
        else:
            # Load XOR bitmap
            try:
                image = BmpImagePlugin.DibImageFile(image_file)
            except IOError:
                return
            if image.mode == 'RGBA':
                # Windows XP 32-bit color depth icon without AND bitmap
                pass
            else:
                # Patch up the bitmap height
                image.size = image.size[0], image.size[1] >> 1
                d, e, o, a = image.tile[0]
                image.tile[0] = d, (0, 0) + image.size, o, a

                # Calculate AND bitmap dimensions. See
                # http://en.wikipedia.org/w/index.php?oldid=264236948#Pixel_storage
                # for description
                offset = o + a[1] * image.size[1]
Example #15
0
    def load_icon(self, image_file, index=None):
        '''
        DEPRECATED

        Load Windows ICO image.

        See http://en.wikipedia.org/w/index.php?oldid=264332061 for file format
        description.

        Cribbed and modified from http://djangosnippets.org/snippets/1287/
        '''
        try:
            image_file.seek(0)
            header = struct.unpack('<3H', image_file.read(6))
        except Exception:
            return

        # Check magic
        if header[:2] != (0, 1):
            return

        # Collect icon directories
        directories = []
        for i in range(header[2]):
            directory = list(struct.unpack('<4B2H2I', image_file.read(16)))
            for j in range(3):
                if not directory[j]:
                    directory[j] = 256

            directories.append(directory)

        if index is None:
            # Select best icon
            directory = max(directories, key=operator.itemgetter(slice(0, 3)))
        else:
            directory = directories[index]

        # Seek to the bitmap data
        image_file.seek(directory[7])

        prefix = image_file.read(16)
        image_file.seek(-16, 1)

        if PngImagePlugin._accept(prefix):
            # Windows Vista icon with PNG inside
            try:
                image = PngImagePlugin.PngImageFile(image_file)
            except IOError:
                return
        else:
            # Load XOR bitmap
            try:
                image = BmpImagePlugin.DibImageFile(image_file)
            except IOError:
                return
            if image.mode == 'RGBA':
                # Windows XP 32-bit color depth icon without AND bitmap
                pass
            else:
                # Patch up the bitmap height
                image.size = image.size[0], image.size[1] >> 1
                d, e, o, a = image.tile[0]
                image.tile[0] = d, (0, 0) + image.size, o, a

                # Calculate AND bitmap dimensions. See
                # http://en.wikipedia.org/w/index.php?oldid=264236948#Pixel_storage
                # for description
                offset = o + a[1] * image.size[1]
                stride = ((image.size[0] + 31) >> 5) << 2
                size = stride * image.size[1]

                # Load AND bitmap
                image_file.seek(offset)
                string = image_file.read(size)
                mask = Image.frombytes('1', image.size, string, 'raw',
                                       ('1;I', stride, -1))

                image = image.convert('RGBA')
                image.putalpha(mask)

        return image