def _save(im, fp, filename):

    if _imaging_gif:
        # call external driver
        try:
            _imaging_gif.save(im, fp, filename)
            return
        except IOError:
            pass  # write uncompressed file

    try:
        rawmode = RAWMODE[im.mode]
        imOut = im
    except KeyError:
        # convert on the fly (EXPERIMENTAL -- I'm not sure PIL
        # should automatically convert images on save...)
        if Image.getmodebase(im.mode) == "RGB":
            imOut = im.convert("P")
            rawmode = "P"
        else:
            imOut = im.convert("L")
            rawmode = "L"

    # header
    for s in getheader(imOut, im.encoderinfo):
        fp.write(s)

    flags = 0

    try:
        interlace = im.encoderinfo["interlace"]
    except:
        # default is on (since we're writing uncompressed images)
        interlace = 1
        flags = flags | 64

    # local image header
    fp.write(
        "," + o16(0) + o16(0) + o16(im.size[0]) + o16(im.size[1]) + chr(flags) + chr(8)  # bounding box  # size  # flags
    )  # bits

    imOut.encoderconfig = (8, interlace)

    ImageFile._save(imOut, fp, [("gif", (0, 0) + im.size, 0, rawmode)])

    fp.write("\0")  # end of image data

    fp.write(";")  # end of file

    try:
        fp.flush()
    except:
        pass
Beispiel #2
0
def getdata(im, offset = (0, 0), **params):
    """Return a list of strings representing this image.
       The first string is a local image header, the rest contains
       encoded image data."""

    class collector:
        data = []
        def write(self, data):
            self.data.append(data)

    im.load() # make sure raster data is available

    fp = collector()

    try:
        im.encoderinfo = params

        # local image header
        fp.write("," +
                 o16(offset[0]) +       # offset
                 o16(offset[1]) +
                 o16(im.size[0]) +      # size
                 o16(im.size[1]) +
                 chr(0) +               # flags
                 chr(8))                # bits

        ImageFile._save(im, fp, [("gif", (0,0)+im.size, 0, RAWMODE[im.mode])])

        fp.write("\0") # end of image data

    finally:
        del im.encoderinfo

    return fp.data
def _save(im, fp, filename, check=0):

    try:
        type, rawmode = SAVE[im.mode]
    except KeyError:
        raise ValueError, "Cannot save %s images as IM" % im.mode

    try:
        frames = im.encoderinfo["frames"]
    except KeyError:
        frames = 1

    if check:
        return check

    fp.write("Image type: %s image\r\n" % type)
    if filename:
        fp.write("Name: %s\r\n" % filename)
    fp.write("Image size (x*y): %d*%d\r\n" % im.size)
    fp.write("File size (no of images): %d\r\n" % frames)
    if im.mode == "P":
        fp.write("Lut: 1\r\n")
    fp.write("\000" * (511-fp.tell()) + "\032")
    if im.mode == "P":
        fp.write(im.im.getpalette("RGB", "RGB;L")) # 768 bytes
    ImageFile._save(im, fp, [("raw", (0,0)+im.size, 0, (rawmode, 0, -1))])
def _save(im, fp, filename):

    if im.mode != "1":
        raise IOError, "cannot write mode %s as MSP" % im.mode

    # create MSP header
    header = [0] * 16

    header[0], header[1] = i16("Da"), i16("nM") # version 1
    header[2], header[3] = im.size
    header[4], header[5] = 1, 1
    header[6], header[7] = 1, 1
    header[8], header[9] = im.size

    sum = 0
    for h in header:
        sum = sum ^ h
    header[12] = sum # FIXME: is this the right field?

    # header
    for h in header:
        fp.write(o16(h))

    # image body
    ImageFile._save(im, fp, [("raw", (0,0)+im.size, 32, ("1", 0, 1))])
Beispiel #5
0
    def update(self):
        self.images = []
        self.images_ui.clear()
        path = self.selecter.getPath()
        files = []
        files = os.listdir(path)
        #        print "update_path:" + path
        if path != "/":
            files.insert(0, "..")

        for f in files:
            # Create QCustomQWidget
            full_path = os.path.join(self.selecter.getPath(), f)
            #            print full_path
            myQCustomQWidget = ImageFile(full_path)
            # Create QListWidgetItem
            myQListWidgetItem = QtGui.QListWidgetItem(self.images_ui)
            # Set size hint#        self.update()
            myQListWidgetItem.setSizeHint(myQCustomQWidget.sizeHint())  #
            myQListWidgetItem.setData(0, QtCore.QVariant(myQCustomQWidget))
            # Add QListWidgetItem into QListWidget#        self.images_ui.itemClicked.connect(self.itemClicked)
            self.images_ui.addItem(
                myQListWidgetItem)  #        self.setShown(True)
            self.images_ui.setItemWidget(
                myQListWidgetItem, myQCustomQWidget)  #        self.show()
            self.images.append(myQCustomQWidget)
def _save(im, fp, filename):

    if im.mode != "1":
        raise IOError, "cannot write mode %s as MSP" % im.mode

    # create MSP header
    header = [0] * 16

    header[0], header[1] = i16("Da"), i16("nM")  # version 1
    header[2], header[3] = im.size
    header[4], header[5] = 1, 1
    header[6], header[7] = 1, 1
    header[8], header[9] = im.size

    sum = 0
    for h in header:
        sum = sum ^ h
    header[12] = sum  # FIXME: is this the right field?

    # header
    for h in header:
        fp.write(o16(h))

    # image body
    ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 32, ("1", 0, 1))])
def _save(im, fp, filename):

    try:
        rawmode = RAWMODE[im.mode]
    except KeyError:
        raise IOError("cannot write mode %s as JPEG" % im.mode)

    info = im.encoderinfo

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

    # get keyword arguments
    im.encoderconfig = (
        info.get("quality", 0),
        # "progressive" is the official name, but older documentation
        # says "progression"
        # FIXME: issue a warning if the wrong form is used (post-1.1.5)
        info.has_key("progressive") or info.has_key("progression"),
        info.get("smooth", 0),
        info.has_key("optimize"),
        info.get("streamtype", 0),
        dpi[0], dpi[1]
        )

    ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
Beispiel #8
0
def _save(im, fp, filename, check=0):

    try:
        rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
    except KeyError:
        raise IOError("cannot write mode %s as TGA" % im.mode)

    if check:
        return check

    if colormaptype:
        colormapfirst, colormaplength, colormapentry = 0, 256, 24
    else:
        colormapfirst, colormaplength, colormapentry = 0, 0, 0

    if im.mode == "RGBA":
        flags = 8
    else:
        flags = 0

    orientation = im.info.get("orientation", -1)
    if orientation > 0:
        flags = flags | 0x20

    fp.write("\000" + chr(colormaptype) + chr(imagetype) + o16(colormapfirst) +
             o16(colormaplength) + chr(colormapentry) + o16(0) + o16(0) +
             o16(im.size[0]) + o16(im.size[1]) + chr(bits) + chr(flags))

    if colormaptype:
        fp.write(im.im.getpalette("RGB", "BGR"))

    ImageFile._save(im, fp,
                    [("raw", (0, 0) + im.size, 0, (rawmode, 0, orientation))])
def _save(im, fp, filename):

    try:
        rawmode = RAWMODE[im.mode]
    except KeyError:
        raise IOError("cannot write mode %s as JPEG" % im.mode)

    info = im.encoderinfo

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

    # get keyword arguments
    im.encoderconfig = (
        info.get("quality", 0),
        # "progressive" is the official name, but older documentation
        # says "progression"
        # FIXME: issue a warning if the wrong form is used (post-1.1.5)
        info.has_key("progressive") or info.has_key("progression"),
        info.get("smooth", 0),
        info.has_key("optimize"),
        info.get("streamtype", 0),
        dpi[0],
        dpi[1])

    ImageFile._save(im, fp, [("jpeg", (0, 0) + im.size, 0, rawmode)])
def saveStack(imstack, filename):
    hdr_stack = makeSpiderHeaderOverall(imstack)
    if len(hdr_stack) < 256:
        raise IOError, "Error creating Spider 2D stack header"
    # write the SPIDER header
    try:
        fp = open(filename, 'wb')
    except:
        raise IOError, "Unable to open %s for writing" % filename
    fp.writelines(hdr_stack)

    rawmode = "F;32NF"  #32-bit native floating point
    ct = 0
    for im in imstack:
        ct += 1  # numbering of stacked images
        if im.mode[0] != "F":
            im = im.convert('F')
        hdr = makeSpiderHeaderInStack(im, ct)  # h[27]=ct
        if len(hdr) < 256:
            raise IOError, "Error creating Spider header"
        fp.writelines(hdr)
        #ims = im.tostring()
        #fp.write(ims)
        ImageFile._save(im, fp,
                        [("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))])
    fp.close()
Beispiel #11
0
def _save(im, fp, filename, check=0):

    try:
        type, rawmode = SAVE[im.mode]
    except KeyError:
        raise ValueError("Cannot save {0} images as IM".format(im.mode))

    try:
        frames = im.encoderinfo["frames"]
    except KeyError:
        frames = 1

    if check:
        return check

    data = []

    data.append("Image type: {0} image\r\n".format(type))
    if filename:
        data.append("Name: {0}\r\n".format(filename))
    data.append("Image size (x*y): {size[0]}*{size[1]}\r\n".format(size=im.size))
    data.append("File size (no of images): {0}\r\n".format(frames))
    if im.mode == "P":
        data.append("Lut: 1\r\n")
    fp.write(''.join(data).encode('latin_1', errors='replace'))
    fp.write(b"\x00" * (511-fp.tell()) + b"\x1a")
    if im.mode == "P":
        fp.write(im.im.getpalette("RGB", "RGB;L")) # 768 bytes
    ImageFile._save(im, fp, [("raw", (0,0)+im.size, 0, (rawmode, 0, -1))])
def getdata(im, offset=(0, 0), **params):
    """Return a list of strings representing this image.
       The first string is a local image header, the rest contains
       encoded image data."""
    class collector:
        data = []

        def write(self, data):
            self.data.append(data)

    im.load()  # make sure raster data is available

    fp = collector()

    try:
        im.encoderinfo = params

        # local image header
        fp.write("," + o16(offset[0]) +  # offset
                 o16(offset[1]) + o16(im.size[0]) +  # size
                 o16(im.size[1]) + chr(0) +  # flags
                 chr(8))  # bits

        ImageFile._save(im, fp,
                        [("gif", (0, 0) + im.size, 0, RAWMODE[im.mode])])

        fp.write("\0")  # end of image data

    finally:
        del im.encoderinfo

    return fp.data
Beispiel #13
0
def _save(im, fp, filename, check=0):

    try:
        type, rawmode = SAVE[im.mode]
    except KeyError:
        raise ValueError, "Cannot save %s images as IM" % im.mode

    try:
        frames = im.encoderinfo["frames"]
    except KeyError:
        frames = 1

    if check:
        return check

    fp.write("Image type: %s image\r\n" % type)
    if filename:
        fp.write("Name: %s\r\n" % filename)
    fp.write("Image size (x*y): %d*%d\r\n" % im.size)
    fp.write("File size (no of images): %d\r\n" % frames)
    if im.mode == "P":
        fp.write("Lut: 1\r\n")
    fp.write("\000" * (511 - fp.tell()) + "\032")
    if im.mode == "P":
        fp.write(im.im.getpalette("RGB", "RGB;L"))  # 768 bytes
    ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, -1))])
Beispiel #14
0
def _save(im, fp, filename):
    if im.mode != "RGB":
        raise IOError("cannot write mode %s as WEBP" % im.mode)
    im.encoderconfig = (
        im.encoderinfo.get("quality", 0),
        )
    ImageFile._save(im, fp, [("webp", (0, 0) + im.size, 0, (im.mode,))])
def CreateStereoBag(left_imgs, right_imgs, bagname):
    '''Creates a bag file containing stereo image pairs'''
    bag = rosbag.Bag(bagname, 'w')

    try:
        for i in range(len(left_imgs)):
            print("Adding %s" % left_imgs[i])
            fp_left = open(left_imgs[i], "r")
            p_left = ImageFile.Parser()

            while 1:
                s = fp_left.read(1024)
                if not s:
                    break
                p_left.feed(s)

            im_left = p_left.close()

            fp_right = open(right_imgs[i], "r")
            print("Adding %s" % right_imgs[i])
            p_right = ImageFile.Parser()

            while 1:
                s = fp_right.read(1024)
                if not s:
                    break
                p_right.feed(s)

            im_right = p_right.close()

            Stamp = roslib.rostime.Time.from_sec(time.time())

            Img_left = Image()
            Img_left.header.stamp = Stamp
            Img_left.width = im_left.size[0]
            Img_left.height = im_left.size[1]
            Img_left.encoding = "rgb8"
            Img_left.header.frame_id = "camera/left"
            Img_left_data = [
                pix for pixdata in im_left.getdata() for pix in pixdata
            ]
            Img_left.data = Img_left_data
            Img_right = Image()
            Img_right.header.stamp = Stamp
            Img_right.width = im_right.size[0]
            Img_right.height = im_right.size[1]
            Img_right.encoding = "rgb8"
            Img_right.header.frame_id = "camera/right"
            Img_right_data = [
                pix for pixdata in im_right.getdata() for pix in pixdata
            ]
            Img_right.data = Img_right_data

            bag.write('camera/left/image_raw', Img_left, Stamp)
            bag.write('camera/right/image_raw', Img_right, Stamp)
    finally:
        bag.close()
Beispiel #16
0
def _save(im, fp, filename, check=0):

    try:
        version, bits, planes, rawmode = SAVE[im.mode]
    except KeyError:
        raise ValueError, "Cannot save %s images as PCX" % im.mode

    if check:
        return check

    # bytes per plane
    stride = (im.size[0] * bits + 7) / 8

    # under windows, we could determine the current screen size with
    # "Image.core.display_mode()[1]", but I think that's overkill...

    screen = im.size

    dpi = 100, 100

    # PCX header
    fp.write(
        chr(10)
        + chr(version)
        + chr(1)
        + chr(bits)
        + o16(0)
        + o16(0)
        + o16(im.size[0] - 1)
        + o16(im.size[1] - 1)
        + o16(dpi[0])
        + o16(dpi[1])
        + chr(0) * 24
        + chr(255) * 24
        + chr(0)
        + chr(planes)
        + o16(stride)
        + o16(1)
        + o16(screen[0])
        + o16(screen[1])
        + chr(0) * 54
    )

    assert fp.tell() == 128

    ImageFile._save(im, fp, [("pcx", (0, 0) + im.size, 0, (rawmode, bits * planes))])

    if im.mode == "P":
        # colour palette
        fp.write(chr(12))
        fp.write(im.im.getpalette("RGB", "RGB"))  # 768 bytes
    elif im.mode == "L":
        # greyscale palette
        fp.write(chr(12))
        for i in range(256):
            fp.write(chr(i) * 3)
Beispiel #17
0
def _save(im, fp, filename, eps=1):
    """EPS Writer for the Python Imaging Library."""

    #
    # make sure image data is available
    im.load()

    #
    # determine postscript image mode
    if im.mode == "L":
        operator = (8, 1, "image")
    elif im.mode == "RGB":
        operator = (8, 3, "false 3 colorimage")
    elif im.mode == "CMYK":
        operator = (8, 4, "false 4 colorimage")
    else:
        raise ValueError("image mode is not supported")

    if eps:
        #
        # write EPS header
        fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
        fp.write(b"%%Creator: PIL 0.1 EpsEncode\n")
        #fp.write("%%CreationDate: %s"...)
        fp.write("%%BoundingBox: 0 0 {0[0]} {0[1]}\n".format(im.size).encode(
            'latin_1', errors='replace'))
        fp.write(b"%%Pages: 1\n")
        fp.write(b"%%EndComments\n")
        fp.write(b"%%Page: 1 1\n")
        fp.write("%%ImageData: {0[0]} {0[1]}".format(im.size).encode('latin_1',
            errors='replace'))
        fp.write("{0[0]} {0[1]} 0 1 1 \"{0[2]}\"\n".format(operator).encode(
            'latin_1', errors='replace'))

    #
    # image header
    fp.write(b"gsave\n")
    fp.write(b"10 dict begin\n")
    fp.write("/buf {0} string def\n".format(im.size[0]*operator[1]).encode(
        'latin_1', errors='replace'))
    fp.write("{0[0]} {0[1]} scale\n".format(im.size).encode('latin_1',
        errors='replace'))
    fp.write("{0[0]} {0[1]} 8\n".format(im.size).encode('latin_1',
        errors='replace')) # <= bits
    fp.write("[{0[0]} 0 0 -{0[1]} 0 {0[1]}]\n".format(im.size).encode(
        'latin_1', errors='replace'))
    fp.write(b"{ currentfile buf readhexstring pop } bind\n")
    fp.write("{0[2]}\n".format(operator).encode('latin_1', errors='replace'))

    ImageFile._save(im, fp, [("eps", (0,0)+im.size, 0, None)])

    fp.write(b"\n%%EndBinary\n")
    fp.write(b"grestore end\n")
    fp.flush()
Beispiel #18
0
def _save(im, fp, filename):

    try:
        rawmode = RAWMODE[im.mode]
    except KeyError:
        raise IOError("cannot write mode %s as JPEG" % im.mode)

    info = im.encoderinfo

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

    subsampling = info.get("subsampling", -1)
    if subsampling == "4:4:4":
        subsampling = 0
    elif subsampling == "4:2:2":
        subsampling = 1
    elif subsampling == "4:1:1":
        subsampling = 2

    extra = ""

    icc_profile = info.get("icc_profile")
    if icc_profile:
        ICC_OVERHEAD_LEN = 14
        MAX_BYTES_IN_MARKER = 65533
        MAX_DATA_BYTES_IN_MARKER = MAX_BYTES_IN_MARKER - ICC_OVERHEAD_LEN
        markers = []
        while icc_profile:
            markers.append(icc_profile[:MAX_DATA_BYTES_IN_MARKER])
            icc_profile = icc_profile[MAX_DATA_BYTES_IN_MARKER:]
        i = 1
        for marker in markers:
            size = struct.pack(">H", 2 + ICC_OVERHEAD_LEN + len(marker))
            extra = extra + ("\xFF\xE2" + size + "ICC_PROFILE\0" + chr(i) + chr(len(markers)) + marker)
            i = i + 1

    # get keyword arguments
    im.encoderconfig = (
        info.get("quality", 0),
        # "progressive" is the official name, but older documentation
        # says "progression"
        # FIXME: issue a warning if the wrong form is used (post-1.1.7)
        info.has_key("progressive") or info.has_key("progression"),
        info.get("smooth", 0),
        info.has_key("optimize"),
        info.get("streamtype", 0),
        dpi[0], dpi[1],
        subsampling,
        extra,
        )

    ImageFile.MAXBLOCK = 10000000

    ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
Beispiel #19
0
def _save(im, fp, filename):

    try:
        rawmode = RAWMODE[im.mode]
    except KeyError:
        raise IOError("cannot write mode %s as JPEG" % im.mode)

    info = im.encoderinfo

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

    subsampling = info.get("subsampling", -1)
    if subsampling == "4:4:4":
        subsampling = 0
    elif subsampling == "4:2:2":
        subsampling = 1
    elif subsampling == "4:1:1":
        subsampling = 2

    extra = ""

    icc_profile = info.get("icc_profile")
    if icc_profile:
        ICC_OVERHEAD_LEN = 14
        MAX_BYTES_IN_MARKER = 65533
        MAX_DATA_BYTES_IN_MARKER = MAX_BYTES_IN_MARKER - ICC_OVERHEAD_LEN
        markers = []
        while icc_profile:
            markers.append(icc_profile[:MAX_DATA_BYTES_IN_MARKER])
            icc_profile = icc_profile[MAX_DATA_BYTES_IN_MARKER:]
        i = 1
        for marker in markers:
            size = struct.pack(">H", 2 + ICC_OVERHEAD_LEN + len(marker))
            extra = extra + ("\xFF\xE2" + size + "ICC_PROFILE\0" + chr(i) +
                             chr(len(markers)) + marker)
            i = i + 1

    # get keyword arguments
    im.encoderconfig = (
        info.get("quality", 0),
        # "progressive" is the official name, but older documentation
        # says "progression"
        # FIXME: issue a warning if the wrong form is used (post-1.1.7)
        info.has_key("progressive") or info.has_key("progression"),
        info.get("smooth", 0),
        info.has_key("optimize"),
        info.get("streamtype", 0),
        dpi[0],
        dpi[1],
        subsampling,
        extra,
    )

    ImageFile._save(im, fp, [("jpeg", (0, 0) + im.size, 0, rawmode)])
Beispiel #20
0
def _save(im, fp, filename, eps=1):
    """EPS Writer for the Python Imaging Library."""

    #
    # make sure image data is available
    im.load()

    #
    # determine postscript image mode
    if im.mode == "L":
        operator = (8, 1, "image")
    elif im.mode == "RGB":
        operator = (8, 3, "false 3 colorimage")
    elif im.mode == "CMYK":
        operator = (8, 4, "false 4 colorimage")
    else:
        raise ValueError("image mode is not supported")

    if eps:
        #
        # write EPS header
        fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
        fp.write(b"%%Creator: PIL 0.1 EpsEncode\n")
        #fp.write(b"%%CreationDate: %s"...)
        fp.write(
            bytes("%%%%BoundingBox: 0 0 %d %d\n" % im.size, encoding='ascii'))
        fp.write(b"%%Pages: 1\n")
        fp.write(b"%%EndComments\n")
        fp.write(b"%%Page: 1 1\n")
        fp.write(bytes("%%ImageData: %d %d " % im.size, encoding='ascii'))
        fp.write(bytes("%d %d 0 1 1 \"%s\"\n" % operator, encoding='ascii'))

    #
    # image header
    fp.write(b"gsave\n")
    fp.write(b"10 dict begin\n")
    fp.write(
        bytes("/buf %d string def\n" % (im.size[0] * operator[1]),
              encoding='ascii'))
    fp.write(bytes("%d %d scale\n" % im.size, encoding='ascii'))
    fp.write(bytes("%d %d 8\n" % im.size, encoding='ascii'))  # <= bits
    fp.write(
        bytes("[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1], im.size[1]),
              encoding='ascii'))
    fp.write(b"{ currentfile buf readhexstring pop } bind\n")
    fp.write(bytes("%s\n" % operator[2], encoding='ascii'))

    ImageFile._save(im, fp, [("eps", (0, 0) + im.size, 0, None)])

    fp.write(b"\n%%%%EndBinary\n")
    fp.write(b"grestore end\n")
    fp.flush()
Beispiel #21
0
def _save(im, fp, filename, check=0):
    try:
        version, bits, planes, rawmode = SAVE[im.mode]
    except KeyError:
        raise ValueError("Cannot save %s images as WBMP" % im.mode)

    if check:
        return check

    width, height = im.size
    # Write header
    fp.write (chr(0) + chr(0) + _tomb(width) + _tomb(height))
    # Write data
    ImageFile._save(im, fp, [("raw", (0,0) + im.size, 0, (rawmode, 0, 1))])
def _save(im, fp, filename, check=0):
    try:
        version, bits, planes, rawmode = SAVE[im.mode]
    except KeyError:
        raise ValueError("Cannot save %s images as WBMP" % im.mode)

    if check:
        return check

    width, height = im.size
    # Write header
    fp.write(chr(0) + chr(0) + _tomb(width) + _tomb(height))
    # Write data
    ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))])
Beispiel #23
0
def _save(im, fp, filename, eps=1):
    """EPS Writer for the Python Imaging Library."""

    #
    # make sure image data is available
    im.load()

    #
    # determine postscript image mode
    if im.mode == "L":
        operator = (8, 1, "image")
    elif im.mode == "RGB":
        operator = (8, 3, "false 3 colorimage")
    elif im.mode == "CMYK":
        operator = (8, 4, "false 4 colorimage")
    else:
        raise ValueError("image mode is not supported")

    if eps:
        #
        # write EPS header
        fp.write(b"%!PS-Adobe-3.0 EPSF-3.0\n")
        fp.write(b"%%Creator: PIL 0.1 EpsEncode\n")
        #fp.write(b"%%CreationDate: %s"...)
        fp.write(bytes("%%%%BoundingBox: 0 0 %d %d\n" % im.size,
            encoding='ascii'))
        fp.write(b"%%Pages: 1\n")
        fp.write(b"%%EndComments\n")
        fp.write(b"%%Page: 1 1\n")
        fp.write(bytes("%%ImageData: %d %d " % im.size, encoding='ascii'))
        fp.write(bytes("%d %d 0 1 1 \"%s\"\n" % operator, encoding='ascii'))

    #
    # image header
    fp.write(b"gsave\n")
    fp.write(b"10 dict begin\n")
    fp.write(bytes("/buf %d string def\n" % (im.size[0] * operator[1]),
        encoding='ascii'))
    fp.write(bytes("%d %d scale\n" % im.size, encoding='ascii'))
    fp.write(bytes("%d %d 8\n" % im.size, encoding='ascii')) # <= bits
    fp.write(bytes("[%d 0 0 -%d 0 %d]\n" % (im.size[0], im.size[1],
        im.size[1]), encoding='ascii'))
    fp.write(b"{ currentfile buf readhexstring pop } bind\n")
    fp.write(bytes("%s\n" % operator[2], encoding='ascii'))

    ImageFile._save(im, fp, [("eps", (0,0)+im.size, 0, None)])

    fp.write(b"\n%%%%EndBinary\n")
    fp.write(b"grestore end\n")
    fp.flush()
Beispiel #24
0
def _save(im, fp, filename):
    if im.mode == "1":
        rawmode, head = "1;I", "P4"
    elif im.mode == "L":
        rawmode, head = "L", "P5"
    elif im.mode == "RGB":
        rawmode, head = "RGB", "P6"
    elif im.mode == "RGBA":
        rawmode, head = "RGB", "P6"
    else:
        raise IOError, "cannot write mode %s as PPM" % im.mode
    fp.write(head + "\n%d %d\n" % im.size)
    if head != "P4":
        fp.write("255\n")
    ImageFile._save(im, fp, [("raw", (0, 0) + im.size, 0, (rawmode, 0, 1))])
Beispiel #25
0
def _save(im, fp, filename):
    if im.mode == "1":
        rawmode, head = "1;I", "P4"
    elif im.mode == "L":
        rawmode, head = "L", "P5"
    elif im.mode == "RGB":
        rawmode, head = "RGB", "P6"
    elif im.mode == "RGBA":
        rawmode, head = "RGB", "P6"
    else:
        raise IOError, "cannot write mode %s as PPM" % im.mode
    fp.write(head + "\n%d %d\n" % im.size)
    if head != "P4":
        fp.write("255\n")
    ImageFile._save(im, fp, [("raw", (0,0)+im.size, 0, (rawmode, 0, 1))])
Beispiel #26
0
def _save(im, fp, filename):
    if im.mode == "1":
        rawmode, head = "1;I", b"P4"
    elif im.mode == "L":
        rawmode, head = "L", b"P5"
    elif im.mode == "RGB":
        rawmode, head = "RGB", b"P6"
    elif im.mode == "RGBA":
        rawmode, head = "RGB", b"P6"
    else:
        raise IOError("cannot write mode %s as PPM" % im.mode)
    fp.write(head + bytes("\n%d %d\n" % im.size, encoding='ascii'))
    if head != b"P4":
        fp.write(b"255\n")
    ImageFile._save(im, fp, [("raw", (0,0)+im.size, 0, (rawmode, 0, 1))])
Beispiel #27
0
def _fetch_image_size(url, referer):
    """Return the size of an image by URL downloading as little as possible."""

    request = _initialize_request(url, referer)
    if not request:
        return None

    parser = ImageFile.Parser()
    response = None
    try:
        response = urllib2.urlopen(request)

        while True:
            chunk = response.read(1024)
            if not chunk:
                break

            parser.feed(chunk)
            if parser.image:
                return parser.image.size
    except urllib2.URLError:
        return None
    finally:
        if response:
            response.close()
Beispiel #28
0
def _save(im, fp, filename):
    if im.mode == "1":
        rawmode, head = "1;I", "P4"
    elif im.mode == "L":
        rawmode, head = "L", "P5"
    elif im.mode == "RGB":
        rawmode, head = "RGB", "P6"
    elif im.mode == "RGBA":
        rawmode, head = "RGB", "P6"
    else:
        raise IOError("cannot write mode {0} as PPM".format(im.mode))
    fp.write(head + "\n{0} {1}\n".format(*im.size).encode('latin_1',
        errors='replace'))
    if head != "P4":
        fp.write(b"255\n")
    ImageFile._save(im, fp, [("raw", (0,0)+im.size, 0, (rawmode, 0, 1))])
Beispiel #29
0
def recog(data, threshold=140):
    p = ImageFile.Parser()
    p.feed(data)
    im = p.close()
    imgry = im.convert('L')
    out = imgry.point(lambda i: 0 if i < threshold else 255)
    return image_to_string(out)
def getimagesize(url):
    """
    Attempts to determine an image's width and height, and returns a string
    suitable for use in an <img> tag, or None in case of failure.
    Requires that PIL is installed.

    >>> getimagesize("http://www.google.com/intl/en_ALL/images/logo.gif")
    ... #doctest: +ELLIPSIS, +SKIP
    'width="..." height="..."'

    """

    try:
        import ImageFile
        import urllib2
    except ImportError:
        return None

    try:
        p = ImageFile.Parser()
        f = urllib2.urlopen(url)
        while True:
            s = f.read(1024)
            if not s:
                break
            p.feed(s)
            if p.image:
                return 'width="%i" height="%i"' % p.image.size
    except (IOError, ValueError):
        return None
Beispiel #31
0
    def analyse_png(self, png_name):
        f = self.get_data(png_name)
        buf = f.read()
        f.close()

        p = ImageFile.Parser()
        p.feed(buf)
        im = p.close()

        self.total_pixels += im.size[0] * im.size[1]

        if png_name.endswith('.jpg'):
            notice('File %s is already compressed' % png_name)
            return False

        if len(buf) < self.size_threshold:
            notice('File %s does not meet size threshold (size is %d)' %
                   (png_name, len(buf)))
            return False

        if self.force_regex.match(png_name):
            warning('File %s will be forced' % png_name)
        elif self.has_transparency(im):
            notice('File %s has transparent pixels' % png_name)
            if len(buf) >= self.size_warning_threshold:
                warning('Transparent image is quite large: %s (%d bytes)' %
                        (png_name, len(buf)))
            return False

        ss = StringIO.StringIO()
        try:
            im.save(ss, 'JPEG', quality=self.compression_level)
        except IOError, ex:
            warning('Unable to convert %s to JPEG: %s' % (png_name, ex))
            return False
def SOF(self, marker):
    #
    # Start of frame marker.  Defines the size and mode of the
    # image.  JPEG is colour blind, so we use some simple
    # heuristics to map the number of layers to an appropriate
    # mode.  Note that this could be made a bit brighter, by
    # looking for JFIF and Adobe APP markers.

    n = i16(self.fp.read(2))-2
    s = ImageFile._safe_read(self.fp, n)
    self.size = i16(s[3:]), i16(s[1:])

    self.bits = ord(s[0])
    if self.bits != 8:
        raise SyntaxError("cannot handle %d-bit layers" % self.bits)

    self.layers = ord(s[5])
    if self.layers == 1:
        self.mode = "L"
    elif self.layers == 3:
        self.mode = "RGB"
    elif self.layers == 4:
        self.mode = "CMYK"
    else:
        raise SyntaxError("cannot handle %d-layer images" % self.layers)

    if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]:
        self.info["progression"] = 1

    for i in range(6, len(s), 3):
        t = s[i:i+3]
        # 4-tuples: id, vsamp, hsamp, qtable
        self.layer.append((t[0], ord(t[1])/16, ord(t[1])&15, ord(t[2])))
Beispiel #33
0
    def get_picture(self):
        if self.stream_file is None:
            return None

        image_parser = ImageFile.Parser()
        self.stream_file.readline() # skip boundary
        self.stream_file.readline() # Content-type
        p = self.stream_file.readline() # Content-Length
        try:
            cl = int(p[p.find(' ') + 1:-2])
        except ValueError:
            self.stream_file = None
            return None

        self.stream_file.readline() # Empty

        image_parser.feed(self.stream_file.read(cl))
        image = image_parser.close()
        surface = pygame.image.fromstring(
                image.tostring(),
                image.size,
                image.mode)
        self.stream_file.readline() # skip eol
        self.stream_file.readline() # skip eol
        return surface
def CreateBag(imgs,bagname):
    '''Creates a bag file with camera images'''
    bag =rosbag.Bag(bagname, 'w')

    try:
        for i in range(len(imgs)):
            print("Adding %s" % imgs[i])
            fp = open( imgs[i], "r" )
            p = ImageFile.Parser()

            while 1:
                s = fp.read(1024)
                if not s:
                    break 
                p.feed(s)

            im = p.close()
            if im.mode != "RGB":
                im=im.convert("RGB")
            Stamp = rospy.rostime.Time.from_sec(time.time())
            Img = Image()
            Img.header.stamp = Stamp
            Img.width = im.size[0]
            Img.height = im.size[1]
            Img.encoding = "rgb8"
            Img.step = Img.width *3;
            Img.header.frame_id = "camera"
            Img_data = [pix for pixdata in im.getdata() for pix in pixdata]
            Img.data = Img_data

            bag.write('/camera/image', Img, Stamp)
    finally:
        bag.close()       
def CreateMonoBag(imgs, bagname):
    '''Creates a bag file with camera images'''
    bag = rosbag.Bag(bagname, 'w')

    try:
        for i in range(len(imgs)):
            print("Adding %s" % imgs[i])
            fp = open(imgs[i], "r")
            p = ImageFile.Parser()

            while 1:
                s = fp.read(1024)
                if not s:
                    break
                p.feed(s)

            im = p.close()

            #Stamp = rospy.rostime.Time.from_sec(time.time())
            Stamp = rospy.Time.from_sec(time.time())
            Img = Image()
            Img.header.stamp = Stamp
            Img.width = im.size[0]
            Img.height = im.size[1]
            #Img.encoding = "rgb8"
            Img.encoding = "mono8"
            Img.header.frame_id = "camera"
            Img_data = [pix for pixdata in im.getdata() for pix in pixdata]
            #Img_data = [pix for pixdata in [im.getdata()] for pix in pixdata]
            Img.data = Img_data
            #Change "rgb8" encoding to "mono8", and "[pix for pixdata in im.getdata() for pix in pixdata]" to "[pix for pixdata in [im.getdata()] for pix in pixdata]"

            bag.write('camera/image_raw', Img, Stamp)
    finally:
        bag.close()
Beispiel #36
0
def siteconfig(request):

    if request.method == 'GET':
        return render_to_response('admin/siteconfig.html')

    if request.method == 'POST':

        sitename = request.POST.get('sitename')
        keywords = request.POST.get('keywords')
        descriptions = request.POST.get('descriptions')
        copyrightinfo = request.POST.get('copyrightinfo')

        form = PictureForm(request.POST, request.FILES)
        if form.is_valid():
            if 'login' and 'banner' in request.FILES:
                login = request.FILES["login"]
                banner = request.FILES["banner"]
            else:
                login = None
                banner = None
            parser = ImageFile.Parser()
            for chunk in login.chunks() and banner.chunks():
                parser.feed(chunk)

                site = Site()
                site.sitename = sitename
                site.keywords = keywords
                site.descriptions = descriptions
                site.login = login
                site.banner = banner
                site.copyrightinfo = copyrightinfo

                site.save()
        return render_to_response('admin/siteconfig.html')
def SOF(self, marker):
    #
    # Start of frame marker.  Defines the size and mode of the
    # image.  JPEG is colour blind, so we use some simple
    # heuristics to map the number of layers to an appropriate
    # mode.  Note that this could be made a bit brighter, by
    # looking for JFIF and Adobe APP markers.

    n = i16(self.fp.read(2)) - 2
    s = ImageFile._safe_read(self.fp, n)
    self.size = i16(s[3:]), i16(s[1:])

    self.bits = ord(s[0])
    if self.bits != 8:
        raise SyntaxError("cannot handle %d-bit layers" % self.bits)

    self.layers = ord(s[5])
    if self.layers == 1:
        self.mode = "L"
    elif self.layers == 3:
        self.mode = "RGB"
    elif self.layers == 4:
        self.mode = "CMYK"
    else:
        raise SyntaxError("cannot handle %d-layer images" % self.layers)

    if marker in [0xFFC2, 0xFFC6, 0xFFCA, 0xFFCE]:
        self.info["progression"] = 1

    for i in range(6, len(s), 3):
        t = s[i:i + 3]
        # 4-tuples: id, vsamp, hsamp, qtable
        self.layer.append((t[0], ord(t[1]) / 16, ord(t[1]) & 15, ord(t[2])))
    def chunk_PLTE(self, pos, len):

        # palette
        s = ImageFile._safe_read(self.fp, len)
        if self.im_mode == "P":
            self.im_palette = "RGB", s
        return s
    def chunk_PLTE(self, pos, len):

        # palette
        s = ImageFile._safe_read(self.fp, len)
        if self.im_mode == "P":
            self.im_palette = "RGB", s
        return s
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

    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("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(1) + o32(1) +  # resolution
        o32(colors) +  # colors used
        o32(colors))  # colors important

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

    if im.mode == "1":
        for i in (0, 255):
            fp.write(chr(i) * 4)
    elif im.mode == "L":
        for i in range(256):
            fp.write(chr(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))])
Beispiel #41
0
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

    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(
        "BM" + o32(offset + image) + o32(0) + o32(offset)  # file type (magic)  # file size  # reserved
    )  # image data offset

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

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

    if im.mode == "1":
        for i in (0, 255):
            fp.write(chr(i) * 4)
    elif im.mode == "L":
        for i in range(256):
            fp.write(chr(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))])
def _save(im, fp, filename):

    try:
        rawmode = RAWMODE[im.mode]
    except KeyError:
        raise IOError, "cannot write mode %s as JPEG" % im.mode

    dpi = _fetch(im.encoderinfo, "dpi", (0, 0))

    # get keyword arguments
    im.encoderconfig = (_fetch(im.encoderinfo, "quality", 0),
                        im.encoderinfo.has_key("progressive"),
                        _fetch(im.encoderinfo, "smooth", 0),
                        im.encoderinfo.has_key("optimize"),
                        _fetch(im.encoderinfo, "streamtype", 0),
                        dpi[0], dpi[1])

    ImageFile._save(im, fp, [("jpeg", (0,0)+im.size, 0, rawmode)])
def COM(self, marker):
    #
    # Comment marker.  Store these in the APP dictionary.

    n = i16(self.fp.read(2))-2
    s = ImageFile._safe_read(self.fp, n)

    self.app["COM"] = s # compatibility
    self.applist.append(("COM", s))
Beispiel #44
0
def LoadCompressed(data):
    JpegHeaderSize = ReadUInt32(data, _BLP_HEADER_SIZE)
    Offset, Size = MipMap(data, 0)
    parser = ImageFile.Parser()
    parser.feed(data[_BLP_HEADER_SIZE+4:_BLP_HEADER_SIZE+4+JpegHeaderSize])
    parser.feed(data[Offset:Offset+Size])
    img = parser.close().convert('RGB')
    r, g, b = img.split()
    return Image.merge("RGB", (b, g, r))
def _save(im, fp, filename, check=0):

    # check if im.mode is compatible with MRC (see Bmp...)

    if check:
        return check

    header = MrcHeader()
    header['width'] = im.size[0]
    header['height'] = im.size[1]
    header['depth'] = 1
    header['mode'] = pilmode_mrcmode[im.mode]
    header.tofile(fp)

    rawmode = mrcmode_rawmode[header['mode']]
    tile = [("raw", (0, 0) + im.size, header.headerlen, (rawmode, 0, 1))]
    print 'savetile:', tile
    ImageFile._save(im, fp, tile)
Beispiel #46
0
def _save(im, fp, filename):

    if im.mode != "1":
        raise IOError, "cannot write mode %s as XBM" % im.mode

    fp.write("#define im_width %d\n" % im.size[0])
    fp.write("#define im_height %d\n" % im.size[1])

    hotspot = im.encoderinfo.get("hotspot")
    if hotspot:
        fp.write("#define im_x_hot %d\n" % hotspot[0])
        fp.write("#define im_y_hot %d\n" % hotspot[1])

    fp.write("static char im_bits[] = {\n")

    ImageFile._save(im, fp, [("xbm", (0,0)+im.size, 0, None)])

    fp.write("};\n")
def _save(im, fp, filename):

    if im.mode != "1":
        raise IOError, "cannot write mode %s as XBM" % im.mode

    fp.write("#define im_width %d\n" % im.size[0])
    fp.write("#define im_height %d\n" % im.size[1])

    hotspot = im.encoderinfo.get("hotspot")
    if hotspot:
        fp.write("#define im_x_hot %d\n" % hotspot[0])
        fp.write("#define im_y_hot %d\n" % hotspot[1])

    fp.write("static char im_bits[] = {\n")

    ImageFile._save(im, fp, [("xbm", (0, 0) + im.size, 0, None)])

    fp.write("};\n")
def _save(im, fp, filename, check=0):

        # check if im.mode is compatible with MRC (see Bmp...)

        if check:
                return check

        header = MrcHeader()
        header['width'] = im.size[0]
        header['height'] = im.size[1]
        header['depth'] = 1
        header['mode'] = pilmode_mrcmode[im.mode]
        header.tofile(fp)

        rawmode = mrcmode_rawmode[header['mode']]
        tile = [("raw", (0,0)+im.size, header.headerlen, (rawmode, 0, 1))]
        print 'savetile:', tile
        ImageFile._save(im, fp, tile)
Beispiel #49
0
def fetchTile(server, z, x, y):
    url = '%s/ctile?style=7&v=1&scale=1&size=1' % server
    url += '&md=backgroundMapnik2&z=%d&x=%d&y=%d' % (z, x, y)
    logging.info('Fetching tile at: %s' % url)
    tile = urllib2.urlopen(url)
    parser = ImageFile.Parser()
    parser.feed(tile.read())
    im = parser.close()
    return im
def COM(self, marker):
    #
    # Comment marker.  Store these in the APP dictionary.

    n = i16(self.fp.read(2)) - 2
    s = ImageFile._safe_read(self.fp, n)

    self.app["COM"] = s  # compatibility
    self.applist.append(("COM", s))
def APP(self, marker):
    #
    # Application marker.  Store these in the APP dictionary.
    # Also look for well-known application markers.

    n = i16(self.fp.read(2))-2
    s = ImageFile._safe_read(self.fp, n)

    app = "APP%d" % (marker&15)

    self.app[app] = s # compatibility
    self.applist.append((app, s))

    if marker == 0xFFE0 and s[:4] == "JFIF":
        # extract JFIF information
        self.info["jfif"] = version = i16(s, 5) # version
        self.info["jfif_version"] = divmod(version, 256)
        # extract JFIF properties
        try:
            jfif_unit = ord(s[7])
            jfif_density = i16(s, 8), i16(s, 10)
        except:
            pass
        else:
            if jfif_unit == 1:
                self.info["dpi"] = jfif_density
            self.info["jfif_unit"] = jfif_unit
            self.info["jfif_density"] = jfif_density
    elif marker == 0xFFE1 and s[:5] == "Exif\0":
        # extract Exif information (incomplete)
        self.info["exif"] = s # FIXME: value will change
    elif marker == 0xFFE2 and s[:5] == "FPXR\0":
        # extract FlashPix information (incomplete)
        self.info["flashpix"] = s # FIXME: value will change
    elif marker == 0xFFE2 and s[:12] == "ICC_PROFILE\0":
        # Since an ICC profile can be larger than the maximum size of
        # a JPEG marker (64K), we need provisions to split it into
        # multiple markers. The format defined by the ICC specifies
        # one or more APP2 markers containing the following data:
        #   Identifying string      ASCII "ICC_PROFILE\0"  (12 bytes)
        #   Marker sequence number  1, 2, etc (1 byte)
        #   Number of markers       Total of APP2's used (1 byte)
        #   Profile data            (remainder of APP2 data)
        # Decoders should use the marker sequence numbers to
        # reassemble the profile, rather than assuming that the APP2
        # markers appear in the correct sequence.
        self.icclist.append(s)
    elif marker == 0xFFEE and s[:5] == "Adobe":
        self.info["adobe"] = i16(s, 5)
        # extract Adobe custom properties
        try:
            adobe_transform = ord(s[1])
        except:
            pass
        else:
            self.info["adobe_transform"] = adobe_transform
Beispiel #52
0
def APP(self, marker):
    #
    # Application marker.  Store these in the APP dictionary.
    # Also look for well-known application markers.

    n = i16(self.fp.read(2)) - 2
    s = ImageFile._safe_read(self.fp, n)

    app = "APP%d" % (marker & 15)

    self.app[app] = s  # compatibility
    self.applist.append((app, s))

    if marker == 0xFFE0 and s[:4] == "JFIF":
        # extract JFIF information
        self.info["jfif"] = version = i16(s, 5)  # version
        self.info["jfif_version"] = divmod(version, 256)
        # extract JFIF properties
        try:
            jfif_unit = ord(s[7])
            jfif_density = i16(s, 8), i16(s, 10)
        except:
            pass
        else:
            if jfif_unit == 1:
                self.info["dpi"] = jfif_density
            self.info["jfif_unit"] = jfif_unit
            self.info["jfif_density"] = jfif_density
    elif marker == 0xFFE1 and s[:5] == "Exif\0":
        # extract Exif information (incomplete)
        self.info["exif"] = s  # FIXME: value will change
    elif marker == 0xFFE2 and s[:5] == "FPXR\0":
        # extract FlashPix information (incomplete)
        self.info["flashpix"] = s  # FIXME: value will change
    elif marker == 0xFFE2 and s[:12] == "ICC_PROFILE\0":
        # Since an ICC profile can be larger than the maximum size of
        # a JPEG marker (64K), we need provisions to split it into
        # multiple markers. The format defined by the ICC specifies
        # one or more APP2 markers containing the following data:
        #   Identifying string      ASCII "ICC_PROFILE\0"  (12 bytes)
        #   Marker sequence number  1, 2, etc (1 byte)
        #   Number of markers       Total of APP2's used (1 byte)
        #   Profile data            (remainder of APP2 data)
        # Decoders should use the marker sequence numbers to
        # reassemble the profile, rather than assuming that the APP2
        # markers appear in the correct sequence.
        self.icclist.append(s)
    elif marker == 0xFFEE and s[:5] == "Adobe":
        self.info["adobe"] = i16(s, 5)
        # extract Adobe custom properties
        try:
            adobe_transform = ord(s[1])
        except:
            pass
        else:
            self.info["adobe_transform"] = adobe_transform
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()
    def load(self, fp):
        # load tag dictionary

        self.reset()

        i16 = self.i16
        i32 = self.i32

        for i in range(i16(fp.read(2))):

            ifd = fp.read(12)

            tag, typ = i16(ifd), i16(ifd, 2)

            if Image.DEBUG:
                import TiffTags

                tagname = TiffTags.TAGS.get(tag, "unknown")
                typname = TiffTags.TYPES.get(typ, "unknown")
                print "tag: %s (%d)" % (tagname, tag),
                print "- type: %s (%d)" % (typname, typ),

            try:
                dispatch = self.load_dispatch[typ]
            except KeyError:
                if Image.DEBUG:
                    print "- unsupported type", typ
                continue  # ignore unsupported type

            size, handler = dispatch

            size = size * i32(ifd, 4)

            # Get and expand tag value
            if size > 4:
                here = fp.tell()
                fp.seek(i32(ifd, 8))
                data = ImageFile._safe_read(fp, size)
                fp.seek(here)
            else:
                data = ifd[8 : 8 + size]

            if len(data) != size:
                raise IOError, "not enough data"

            self.tagdata[tag] = typ, data
            self.tagtype[tag] = typ

            if Image.DEBUG:
                if tag in (COLORMAP, IPTC_NAA_CHUNK, PHOTOSHOP_CHUNK, ICCPROFILE, XMP):
                    print "- value: <table: %d bytes>" % size
                else:
                    print "- value:", self[tag]

        self.next = i32(fp.read(4))
    def chunk_zTXt(self, pos, len):

        # compressed text
        s = ImageFile._safe_read(self.fp, len)
        k, v = string.split(s, "\0", 1)
        comp_method = ord(v[0])
        if comp_method != 0:
            raise SyntaxError("Unknown compression method %s in zTXt chunk" % comp_method)
        import zlib
        self.im_info[k] = self.im_text[k] = zlib.decompress(v[1:])
        return s
    def chunk_tRNS(self, pos, len):

        # transparency
        s = ImageFile._safe_read(self.fp, len)
        if self.im_mode == "P":
            i = string.find(s, chr(0))
            if i >= 0:
                self.im_info["transparency"] = i
        elif self.im_mode == "L":
            self.im_info["transparency"] = i16(s)
        return s
    def chunk_tEXt(self, pos, len):

        # text
        s = ImageFile._safe_read(self.fp, len)
        try:
            k, v = string.split(s, "\0", 1)
        except ValueError:
            k = s; v = "" # fallback for broken tEXt tags
        if k:
            self.im_info[k] = self.im_text[k] = v
        return s
Beispiel #58
0
def _save(im, fp, filename, check=0):

    try:
        rawmode, bits, colormaptype, imagetype = SAVE[im.mode]
    except KeyError:
        raise IOError("cannot write mode %s as TGA" % im.mode)

    if check:
        return check

    if colormaptype:
        colormapfirst, colormaplength, colormapentry = 0, 256, 24
    else:
        colormapfirst, colormaplength, colormapentry = 0, 0, 0

    if im.mode == "RGBA":
        flags = 8
    else:
        flags = 0

    orientation = im.info.get("orientation", -1)
    if orientation > 0:
        flags = flags | 0x20

    fp.write("\000" +
             chr(colormaptype) +
             chr(imagetype) +
             o16(colormapfirst) +
             o16(colormaplength) +
             chr(colormapentry) +
             o16(0) +
             o16(0) +
             o16(im.size[0]) +
             o16(im.size[1]) +
             chr(bits) +
             chr(flags))

    if colormaptype:
        fp.write(im.im.getpalette("RGB", "BGR"))

    ImageFile._save(im, fp, [("raw", (0,0)+im.size, 0, (rawmode, 0, orientation))])
    def chunk_pHYs(self, pos, len):

        # pixels per unit
        s = ImageFile._safe_read(self.fp, len)
        px, py = i32(s), i32(s[4:])
        unit = ord(s[8])
        if unit == 1: # meter
            dpi = int(px * 0.0254 + 0.5), int(py * 0.0254 + 0.5)
            self.im_info["dpi"] = dpi
        elif unit == 0:
            self.im_info["aspect"] = px, py
        return s