Python PIL.ImageFile.ImageFile() Examples

The following are 17 code examples of PIL.ImageFile.ImageFile(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module PIL.ImageFile , or try the search function .
Example #1
Source File: SpiderImagePlugin.py    From lambda-text-extractor with Apache License 2.0 6 votes vote down vote up
def _save(im, fp, filename):
    if im.mode[0] != "F":
        im = im.convert('F')

    hdr = makeSpiderHeader(im)
    if len(hdr) < 256:
        raise IOError("Error creating Spider header")

    # write the SPIDER header
    try:
        fp = open(filename, 'wb')
    except:
        raise IOError("Unable to open %s for writing" % filename)
    fp.writelines(hdr)

    rawmode = "F;32NF"  # 32-bit native floating point
    ImageFile._save(im, fp, [("raw", (0, 0)+im.size, 0, (rawmode, 0, 1))])

    fp.close() 
Example #2
Source File: SpiderImagePlugin.py    From lambda-text-extractor with Apache License 2.0 6 votes vote down vote up
def _save(im, fp, filename):
    if im.mode[0] != "F":
        im = im.convert('F')

    hdr = makeSpiderHeader(im)
    if len(hdr) < 256:
        raise IOError("Error creating Spider header")

    # write the SPIDER header
    try:
        fp = open(filename, 'wb')
    except:
        raise IOError("Unable to open %s for writing" % filename)
    fp.writelines(hdr)

    rawmode = "F;32NF"  # 32-bit native floating point
    ImageFile._save(im, fp, [("raw", (0, 0)+im.size, 0, (rawmode, 0, 1))])

    fp.close() 
Example #3
Source File: transforms.py    From oops with MIT License 6 votes vote down vote up
def __call__(self, img):
        # assuming HWC not CHW
        if isinstance(img, ImageFile.ImageFile):
            img = np.array(img)
        short_side = min(img.shape[:-1])
        # if torch.distributed.get_rank() <= 0:
        #    print(self.scale)
        d = int(self.scale * short_side)
        y, x = img.shape[:-1]
        if not self.center:
            y0, x0 = random.choice([
                (0, 0),
                (y-d, 0),
                (0, x-d),
                (y-d, x-d),
                (int((y-d)/2), int((x-d)/2))
            ])
        else:
            y0, x0 = int((y-d)/2), int((x-d)/2)
        return img[y0:y0+d, x0:x0+d, :] 
Example #4
Source File: image.py    From pdf-annotate with MIT License 5 votes vote down vote up
def resolve_image(image_or_filename):
        if isinstance(image_or_filename, str):
            return PILImage.open(image_or_filename)
        elif isinstance(image_or_filename, ImageFile):
            return image_or_filename
        raise ValueError('Invalid image format: {}'.format(
            image_or_filename.__class__.__name__)) 
Example #5
Source File: SpiderImagePlugin.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def _save(im, fp, filename):
    if im.mode[0] != "F":
        im = im.convert("F")

    hdr = makeSpiderHeader(im)
    if len(hdr) < 256:
        raise OSError("Error creating Spider header")

    # write the SPIDER header
    fp.writelines(hdr)

    rawmode = "F;32NF"  # 32-bit native floating point
    ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))]) 
Example #6
Source File: test_imagefile.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_broken_datastream_without_errors(self):
        if "zip_encoder" not in codecs:
            self.skipTest("PNG (zlib) encoder not available")

        im = Image.open("Tests/images/broken_data_stream.png")

        ImageFile.LOAD_TRUNCATED_IMAGES = True
        try:
            im.load()
        finally:
            ImageFile.LOAD_TRUNCATED_IMAGES = False 
Example #7
Source File: test_imagefile.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_truncated_without_errors(self):
        if "zip_encoder" not in codecs:
            self.skipTest("PNG (zlib) encoder not available")

        im = Image.open("Tests/images/truncated_image.png")

        ImageFile.LOAD_TRUNCATED_IMAGES = True
        try:
            im.load()
        finally:
            ImageFile.LOAD_TRUNCATED_IMAGES = False 
Example #8
Source File: test_imagefile.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_raise_ioerror(self):
        self.assertRaises(IOError, ImageFile.raise_ioerror, 1) 
Example #9
Source File: test_imagefile.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_safeblock(self):
        if "zip_encoder" not in codecs:
            self.skipTest("PNG (zlib) encoder not available")

        im1 = hopper()

        try:
            ImageFile.SAFEBLOCK = 1
            im2 = fromstring(tostring(im1, "PNG"))
        finally:
            ImageFile.SAFEBLOCK = SAFEBLOCK

        self.assert_image_equal(im1, im2) 
Example #10
Source File: test_imagefile.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_ico(self):
        with open('Tests/images/python.ico', 'rb') as f:
            data = f.read()
        with ImageFile.Parser() as p:
            p.feed(data)
            self.assertEqual((48, 48), p.image.size) 
Example #11
Source File: SpiderImagePlugin.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _save(im, fp, filename):
    if im.mode[0] != "F":
        im = im.convert('F')

    hdr = makeSpiderHeader(im)
    if len(hdr) < 256:
        raise IOError("Error creating Spider header")

    # write the SPIDER header
    fp.writelines(hdr)

    rawmode = "F;32NF"  # 32-bit native floating point
    ImageFile._save(im, fp, [("raw", (0, 0)+im.size, 0, (rawmode, 0, 1))]) 
Example #12
Source File: SpiderImagePlugin.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _save(im, fp, filename):
    if im.mode[0] != "F":
        im = im.convert("F")

    hdr = makeSpiderHeader(im)
    if len(hdr) < 256:
        raise OSError("Error creating Spider header")

    # write the SPIDER header
    fp.writelines(hdr)

    rawmode = "F;32NF"  # 32-bit native floating point
    ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))]) 
Example #13
Source File: SpiderImagePlugin.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _save(im, fp, filename):
    if im.mode[0] != "F":
        im = im.convert("F")

    hdr = makeSpiderHeader(im)
    if len(hdr) < 256:
        raise OSError("Error creating Spider header")

    # write the SPIDER header
    fp.writelines(hdr)

    rawmode = "F;32NF"  # 32-bit native floating point
    ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))]) 
Example #14
Source File: SpiderImagePlugin.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _save(im, fp, filename):
    if im.mode[0] != "F":
        im = im.convert('F')

    hdr = makeSpiderHeader(im)
    if len(hdr) < 256:
        raise IOError("Error creating Spider header")

    # write the SPIDER header
    fp.writelines(hdr)

    rawmode = "F;32NF"  # 32-bit native floating point
    ImageFile._save(im, fp, [("raw", (0, 0)+im.size, 0, (rawmode, 0, 1))]) 
Example #15
Source File: test_imagefile.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_parser(self):

        def roundtrip(format):

            im = hopper("L").resize((1000, 1000))
            if format in ("MSP", "XBM"):
                im = im.convert("1")

            test_file = BytesIO()

            im.copy().save(test_file, format)

            data = test_file.getvalue()

            parser = ImageFile.Parser()
            parser.feed(data)
            imOut = parser.close()

            return im, imOut

        self.assert_image_equal(*roundtrip("BMP"))
        im1, im2 = roundtrip("GIF")
        self.assert_image_similar(im1.convert('P'), im2, 1)
        self.assert_image_equal(*roundtrip("IM"))
        self.assert_image_equal(*roundtrip("MSP"))
        if "zip_encoder" in codecs:
            try:
                # force multiple blocks in PNG driver
                ImageFile.MAXBLOCK = 8192
                self.assert_image_equal(*roundtrip("PNG"))
            finally:
                ImageFile.MAXBLOCK = MAXBLOCK
        self.assert_image_equal(*roundtrip("PPM"))
        self.assert_image_equal(*roundtrip("TIFF"))
        self.assert_image_equal(*roundtrip("XBM"))
        self.assert_image_equal(*roundtrip("TGA"))
        self.assert_image_equal(*roundtrip("PCX"))

        if EpsImagePlugin.has_ghostscript():
            im1, im2 = roundtrip("EPS")
            # This test fails on Ubuntu 12.04, PPC (Bigendian) It
            # appears to be a ghostscript 9.05 bug, since the
            # ghostscript rendering is wonky and the file is identical
            # to that written on ubuntu 12.04 x64
            # md5sum: ba974835ff2d6f3f2fd0053a23521d4a

            # EPS comes back in RGB:
            self.assert_image_similar(im1, im2.convert('L'), 20)

        if "jpeg_encoder" in codecs:
            im1, im2 = roundtrip("JPEG")  # lossy compression
            self.assert_image(im1, im2.mode, im2.size)

        self.assertRaises(IOError, roundtrip, "PDF") 
Example #16
Source File: image.py    From pdf-annotate with MIT License 4 votes vote down vote up
def make_image_xobject(image):
        """Construct a PdfDict representing the Image XObject, for inserting
        into the AP Resources dict.

        PNGs and GIFs are treated equally - the raw sample values are included
        using PDF's FlateDecode compression format. JPEGs can be included in
        their original form using the DCTDecode filter.

        PNGs with transparency have the alpha channel split out and included as
        an SMask, since PDFs don't natively support transparent PNGs.

        Details about file formats and allowed modes can be found at
        https://pillow.readthedocs.io/en/5.3.x/handbook/image-file-formats.html

        :param str|ImageFile image: Either a str representing the path to the
            image filename, or a PIL.ImageFile.ImageFile object representing
            the image loaded using the PIL library.
        :returns PdfDict: Image XObject
        """
        image = Image.resolve_image(image)
        # PILImage.convert drops the format attribute
        image_format = image.format
        width, height = image.size

        # Normalize images to RGB or grayscale color spaces, and split out the
        # alpha layer into a PDF smask XObject
        image, smask_xobj = Image.convert_to_compatible_image(
            image,
            image_format,
        )

        if image_format in ('PNG', 'GIF'):
            content = Image.make_compressed_image_content(image)
            filter_type = 'FlateDecode'  # TODO use a predictor
        elif image_format == 'JPEG':
            content = Image.make_jpeg_image_content(image)
            filter_type = 'DCTDecode'
        else:
            raise ValueError(
                'Unsupported image format: {}. Supported formats are '
                'PNG, JPEG, and GIF'.format(image.format)
            )

        xobj = PdfDict(
            stream=content,
            BitsPerComponent=8,
            Filter=PdfName(filter_type),
            ColorSpace=Image._get_color_space_name(image),
            Width=width,
            Height=height,
            Subtype=PdfName('Image'),
            Type=PdfName('XObject'),
        )
        if smask_xobj is not None:
            xobj.SMask = smask_xobj
        return xobj 
Example #17
Source File: BmpImagePlugin.py    From console_video with MIT License 4 votes vote down vote up
def _save(im, fp, filename, check=0):
    try:
        rawmode, bits, colors = SAVE[im.mode]
    except KeyError:
        raise IOError("cannot write mode %s as BMP" % im.mode)

    if check:
        return check

    info = im.encoderinfo

    dpi = info.get("dpi", (96, 96))

    # 1 meter == 39.3701 inches
    ppm = tuple(map(lambda x: int(x * 39.3701), dpi))

    stride = ((im.size[0]*bits+7)//8+3) & (~3)
    header = 40  # or 64 for OS/2 version 2
    offset = 14 + header + colors * 4
    image = stride * im.size[1]

    # bitmap header
    fp.write(b"BM" +                      # file type (magic)
             o32(offset+image) +          # file size
             o32(0) +                     # reserved
             o32(offset))                 # image data offset

    # bitmap info header
    fp.write(o32(header) +                # info header size
             o32(im.size[0]) +            # width
             o32(im.size[1]) +            # height
             o16(1) +                     # planes
             o16(bits) +                  # depth
             o32(0) +                     # compression (0=uncompressed)
             o32(image) +                 # size of bitmap
             o32(ppm[0]) + o32(ppm[1]) +  # resolution
             o32(colors) +                # colors used
             o32(colors))                 # colors important

    fp.write(b"\0" * (header - 40))       # padding (for OS/2 format)

    if im.mode == "1":
        for i in (0, 255):
            fp.write(o8(i) * 4)
    elif im.mode == "L":
        for i in range(256):
            fp.write(o8(i) * 4)
    elif im.mode == "P":
        fp.write(im.im.getpalette("RGB", "BGRX"))

    ImageFile._save(im, fp, [("raw", (0, 0)+im.size, 0,
                    (rawmode, stride, -1))])

#
# --------------------------------------------------------------------
# Registry