Python Image 模块,fromstring() 实例源码

我们从Python开源项目中,提取了以下30个代码示例,用于说明如何使用Image.fromstring()

项目:oil    作者:oilshell    | 项目源码 | 文件源码
def fromstring(self,s,width,height,format=imgformat.macrgb):
        """Stuff this pixmap with raw pixel data from a string.
        Supply width, height, and one of the imgformat specifiers."""
        # we only support 16- and 32-bit mac rgb...
        # so convert if necessary
        if format != imgformat.macrgb and format != imgformat.macrgb16:
            # (LATER!)
            raise "NotImplementedError", "conversion to macrgb or macrgb16"
        self.data = s
        self.bounds = (0,0,width,height)
        self.cmpCount = 3
        self.pixelType = QuickDraw.RGBDirect
        if format == imgformat.macrgb:
            self.pixelSize = 32
            self.cmpSize = 8
        else:
            self.pixelSize = 16
            self.cmpSize = 5
        self.rowBytes = width*self.pixelSize/8
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def fromstring(self,s,width,height,format=imgformat.macrgb):
        """Stuff this pixmap with raw pixel data from a string.
        Supply width, height, and one of the imgformat specifiers."""
        # we only support 16- and 32-bit mac rgb...
        # so convert if necessary
        if format != imgformat.macrgb and format != imgformat.macrgb16:
            # (LATER!)
            raise "NotImplementedError", "conversion to macrgb or macrgb16"
        self.data = s
        self.bounds = (0,0,width,height)
        self.cmpCount = 3
        self.pixelType = QuickDraw.RGBDirect
        if format == imgformat.macrgb:
            self.pixelSize = 32
            self.cmpSize = 8
        else:
            self.pixelSize = 16
            self.cmpSize = 5
        self.rowBytes = width*self.pixelSize/8
项目:text-renderer    作者:cjnolet    | 项目源码 | 文件源码
def apply_perspective_surf(self, surf):
        self.invert_surface(surf)
        data = pygame.image.tostring(surf, 'RGBA')
        img = Image.fromstring('RGBA', surf.get_size(), data)
        img = img.transform(img.size, self.affinestate.proj_type,
            self.affinestate.sample_transformation(img.size),
            Image.BICUBIC)
        img = img.transform(img.size, self.perspectivestate.proj_type,
            self.perspectivestate.sample_transformation(img.size),
            Image.BICUBIC)
        im = n.array(img)
        # pyplot.imshow(im)
        # pyplot.show()
        surf = pygame.surfarray.make_surface(im[...,0:3].swapaxes(0,1))
        self.invert_surface(surf)
        return surf
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def fromstring(self,s,width,height,format=imgformat.macrgb):
        """Stuff this pixmap with raw pixel data from a string.
        Supply width, height, and one of the imgformat specifiers."""
        # we only support 16- and 32-bit mac rgb...
        # so convert if necessary
        if format != imgformat.macrgb and format != imgformat.macrgb16:
            # (LATER!)
            raise "NotImplementedError", "conversion to macrgb or macrgb16"
        self.data = s
        self.bounds = (0,0,width,height)
        self.cmpCount = 3
        self.pixelType = QuickDraw.RGBDirect
        if format == imgformat.macrgb:
            self.pixelSize = 32
            self.cmpSize = 8
        else:
            self.pixelSize = 16
            self.cmpSize = 5
        self.rowBytes = width*self.pixelSize/8
项目:CNCGToolKit    作者:cineuse    | 项目源码 | 文件源码
def grab(bbox=None):
    size, data = grabber()
    im = Image.fromstring(
        "RGB", size, data,
        # RGB, 32-bit line padding, origo in lower left corner
        "raw", "BGR", (size[0]*3 + 3) & -4, -1
        )
    if bbox:
        im = im.crop(bbox)
    return im

##
# (New in 1.1.4) Take a snapshot of the clipboard image, if any.
#
# @return An image, a list of filenames, or None if the clipboard does
#     not contain image data or filenames.  Note that if a list is
#     returned, the filenames may not represent image files.
# @since 1.1.4
项目:InstagramPosting    作者:LeviParadis    | 项目源码 | 文件源码
def grab(bbox=None):
    size, data = grabber()
    im = Image.fromstring(
        "RGB", size, data,
        # RGB, 32-bit line padding, origo in lower left corner
        "raw", "BGR", (size[0]*3 + 3) & -4, -1
        )
    if bbox:
        im = im.crop(bbox)
    return im

##
# (New in 1.1.4) Take a snapshot of the clipboard image, if any.
#
# @return An image, a list of filenames, or None if the clipboard does
#     not contain image data or filenames.  Note that if a list is
#     returned, the filenames may not represent image files.
# @since 1.1.4
项目:ngx_status    作者:YoYoAdorkable    | 项目源码 | 文件源码
def grab(bbox=None):
    size, data = grabber()
    im = Image.fromstring(
        "RGB", size, data,
        # RGB, 32-bit line padding, origo in lower left corner
        "raw", "BGR", (size[0]*3 + 3) & -4, -1
        )
    if bbox:
        im = im.crop(bbox)
    return im

##
# (New in 1.1.4) Take a snapshot of the clipboard image, if any.
#
# @return An image, a list of filenames, or None if the clipboard does
#     not contain image data or filenames.  Note that if a list is
#     returned, the filenames may not represent image files.
# @since 1.1.4
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def fromImage(self,im):
        """Initialize this PixMap from a PIL Image object."""
        # We need data in ARGB format; PIL can't currently do that,
        # but it can do RGBA, which we can use by inserting one null
        # up frontpm =
        if im.mode != 'RGBA': im = im.convert('RGBA')
        data = chr(0) + im.tostring()
        self.fromstring(data, im.size[0], im.size[1])
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def toImage(self):
        """Return the contents of this PixMap as a PIL Image object."""
        import Image
        # our tostring() method returns data in ARGB format,
        # whereas Image uses RGBA; a bit of slicing fixes this...
        data = self.tostring()[1:] + chr(0)
        bounds = self.bounds
        return Image.fromstring('RGBA',(bounds[2]-bounds[0],bounds[3]-bounds[1]),data)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def fromImage(self,im):
        """Initialize this PixMap from a PIL Image object."""
        # We need data in ARGB format; PIL can't currently do that,
        # but it can do RGBA, which we can use by inserting one null
        # up frontpm =
        if im.mode != 'RGBA': im = im.convert('RGBA')
        data = chr(0) + im.tostring()
        self.fromstring(data, im.size[0], im.size[1])
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def toImage(self):
        """Return the contents of this PixMap as a PIL Image object."""
        import Image
        # our tostring() method returns data in ARGB format,
        # whereas Image uses RGBA; a bit of slicing fixes this...
        data = self.tostring()[1:] + chr(0)
        bounds = self.bounds
        return Image.fromstring('RGBA',(bounds[2]-bounds[0],bounds[3]-bounds[1]),data)
项目:text-renderer    作者:cjnolet    | 项目源码 | 文件源码
def save_screen_img(pg_surface, fn, quality=100):
    imgstr = pygame.image.tostring(pg_surface, 'RGB')
    im = Image.fromstring('RGB', pg_surface.get_size(), imgstr)
    im.save(fn, quality=quality)
    print fn
项目:text-renderer    作者:cjnolet    | 项目源码 | 文件源码
def get_image(self):
        data = pygame.image.tostring(self.screen, 'RGBA')
        return n.array(Image.fromstring('RGBA', self.screen.get_size(), data))
项目:py-ffmpeg    作者:dandydarcy    | 项目源码 | 文件源码
def displayframe(self,thearray):
      """
      pyffmpeg callback
      """
      _i = thearray.astype(numpy.uint8).copy('C')
      _i_height=_i.shape[0]
      _i_width = _i.shape[1]

      frame = Image.fromstring("RGB",(_i_width,_i_height),_i.data)
      frame = frame.resize(self.size)
      self.screen.set_from_pixbuf(self.image2pixbuf(frame))
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def fromImage(self,im):
        """Initialize this PixMap from a PIL Image object."""
        # We need data in ARGB format; PIL can't currently do that,
        # but it can do RGBA, which we can use by inserting one null
        # up frontpm =
        if im.mode != 'RGBA': im = im.convert('RGBA')
        data = chr(0) + im.tostring()
        self.fromstring(data, im.size[0], im.size[1])
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def toImage(self):
        """Return the contents of this PixMap as a PIL Image object."""
        import Image
        # our tostring() method returns data in ARGB format,
        # whereas Image uses RGBA; a bit of slicing fixes this...
        data = self.tostring()[1:] + chr(0)
        bounds = self.bounds
        return Image.fromstring('RGBA',(bounds[2]-bounds[0],bounds[3]-bounds[1]),data)
项目:CNCGToolKit    作者:cineuse    | 项目源码 | 文件源码
def load(self, im):
            im.fp.seek(0) # rewind
            return Image.fromstring(
                "RGB", im.size,
                Image.core.drawwmf(im.fp.read(), im.size, self.bbox),
                "raw", "BGR", (im.size[0]*3 + 3) & -4, -1
                )
项目:CNCGToolKit    作者:cineuse    | 项目源码 | 文件源码
def open(filename):
    # FIXME: modify to return a WalImageFile instance instead of
    # plain Image object ?

    if hasattr(filename, "read"):
        fp = filename
    else:
        import __builtin__
        fp = __builtin__.open(filename, "rb")

    # read header fields
    header = fp.read(32+24+32+12)
    size = i32(header, 32), i32(header, 36)
    offset = i32(header, 40)

    # load pixel data
    fp.seek(offset)

    im = Image.fromstring("P", size, fp.read(size[0] * size[1]))
    im.putpalette(quake2palette)

    im.format = "WAL"
    im.format_description = "Quake2 Texture"

    # strings are null-terminated
    im.info["name"] = header[:32].split("\0", 1)[0]
    next_name = header[56:56+32].split("\0", 1)[0]
    if next_name:
        im.info["next_name"] = next_name

    return im
项目:actinf    作者:x75    | 项目源码 | 文件源码
def getImage():
  current_image = []
  naoImage = camProxy.getImageRemote(nameId)
  Width = naoImage[0]
  Height = naoImage[1]
  array = naoImage[6]
  image = Image.fromstring("RGB", (Width, Height), array)
  current_image = np.array(image) 
#  current_image = cv2.cvtColor(current_image, cv2.COLOR_RGB2GRAY)
#  current_image = cv2.resize(current_image, (img_size, img_size))
  return current_image
项目:actinf    作者:x75    | 项目源码 | 文件源码
def getImage():
  current_image = []
  naoImage = camProxy.getImageRemote(nameId)
  Width = naoImage[0]
  Height = naoImage[1]
  array = naoImage[6]
  image = Image.fromstring("RGB", (Width, Height), array)
  current_image = np.array(image) 
  current_image = cv2.cvtColor(current_image, cv2.COLOR_RGB2GRAY)
  current_image = cv2.resize(current_image, (img_size, img_size))
  return current_image

# encode the image using the VAE
项目:InstagramPosting    作者:LeviParadis    | 项目源码 | 文件源码
def load(self, im):
            im.fp.seek(0) # rewind
            return Image.fromstring(
                "RGB", im.size,
                Image.core.drawwmf(im.fp.read(), im.size, self.bbox),
                "raw", "BGR", (im.size[0]*3 + 3) & -4, -1
                )
项目:InstagramPosting    作者:LeviParadis    | 项目源码 | 文件源码
def open(filename):
    # FIXME: modify to return a WalImageFile instance instead of
    # plain Image object ?

    if hasattr(filename, "read"):
        fp = filename
    else:
        import __builtin__
        fp = __builtin__.open(filename, "rb")

    # read header fields
    header = fp.read(32+24+32+12)
    size = i32(header, 32), i32(header, 36)
    offset = i32(header, 40)

    # load pixel data
    fp.seek(offset)

    im = Image.fromstring("P", size, fp.read(size[0] * size[1]))
    im.putpalette(quake2palette)

    im.format = "WAL"
    im.format_description = "Quake2 Texture"

    # strings are null-terminated
    im.info["name"] = header[:32].split("\0", 1)[0]
    next_name = header[56:56+32].split("\0", 1)[0]
    if next_name:
        im.info["next_name"] = next_name

    return im
项目:pizza    作者:lammps    | 项目源码 | 文件源码
def save(self,file=None):
    self.w.update()      # force image on screen to be current before saving it

    pstring = glReadPixels(0,0,self.xpixels,self.ypixels,
                           GL_RGBA,GL_UNSIGNED_BYTE)
    snapshot = Image.fromstring("RGBA",(self.xpixels,self.ypixels),pstring)
    snapshot = snapshot.transpose(Image.FLIP_TOP_BOTTOM)

    if not file: file = self.file
    snapshot.save(file + ".png")

  # --------------------------------------------------------------------
项目:ngx_status    作者:YoYoAdorkable    | 项目源码 | 文件源码
def open(filename):
    # FIXME: modify to return a WalImageFile instance instead of
    # plain Image object ?

    if hasattr(filename, "read"):
        fp = filename
    else:
        import __builtin__
        fp = __builtin__.open(filename, "rb")

    # read header fields
    header = fp.read(32+24+32+12)
    size = i32(header, 32), i32(header, 36)
    offset = i32(header, 40)

    # load pixel data
    fp.seek(offset)

    im = Image.fromstring("P", size, fp.read(size[0] * size[1]))
    im.putpalette(quake2palette)

    im.format = "WAL"
    im.format_description = "Quake2 Texture"

    # strings are null-terminated
    im.info["name"] = header[:32].split("\0", 1)[0]
    next_name = header[56:56+32].split("\0", 1)[0]
    if next_name:
        im.info["next_name"] = next_name

    return im
项目:CNCGToolKit    作者:cineuse    | 项目源码 | 文件源码
def _load_bitmaps(self, metrics):

        #
        # bitmap data

        bitmaps = []

        fp, format, i16, i32 = self._getformat(PCF_BITMAPS)

        nbitmaps = i32(fp.read(4))

        if nbitmaps != len(metrics):
            raise IOError, "Wrong number of bitmaps"

        offsets = []
        for i in range(nbitmaps):
            offsets.append(i32(fp.read(4)))

        bitmapSizes = []
        for i in range(4):
            bitmapSizes.append(i32(fp.read(4)))

        byteorder = format & 4 # non-zero => MSB
        bitorder  = format & 8 # non-zero => MSB
        padindex  = format & 3

        bitmapsize = bitmapSizes[padindex]
        offsets.append(bitmapsize)

        data = fp.read(bitmapsize)

        pad  = BYTES_PER_ROW[padindex]
        mode = "1;R"
        if bitorder:
            mode = "1"

        for i in range(nbitmaps):
            x, y, l, r, w, a, d, f = metrics[i]
            b, e = offsets[i], offsets[i+1]
            bitmaps.append(
                Image.fromstring("1", (x, y), data[b:e], "raw", mode, pad(x))
                )

        return bitmaps
项目:CNCGToolKit    作者:cineuse    | 项目源码 | 文件源码
def bdf_char(f):

    # skip to STARTCHAR
    while 1:
        s = f.readline()
        if not s:
            return None
        if s[:9] == "STARTCHAR":
            break
    id = string.strip(s[9:])

    # load symbol properties
    props = {}
    while 1:
        s = f.readline()
        if not s or s[:6] == "BITMAP":
            break
        i = string.find(s, " ")
        props[s[:i]] = s[i+1:-1]

    # load bitmap
    bitmap = []
    while 1:
        s = f.readline()
        if not s or s[:7] == "ENDCHAR":
            break
        bitmap.append(s[:-1])
    bitmap = string.join(bitmap, "")

    [x, y, l, d] = map(int, string.split(props["BBX"]))
    [dx, dy] = map(int, string.split(props["DWIDTH"]))

    bbox = (dx, dy), (l, -d-y, x+l, -d), (0, 0, x, y)

    try:
        im = Image.fromstring("1", (x, y), bitmap, "hex", "1")
    except ValueError:
        # deal with zero-width characters
        im = Image.new("1", (x, y))

    return id, int(props["ENCODING"]), bbox, im

##
# Font file plugin for the X11 BDF format.
项目:InstagramPosting    作者:LeviParadis    | 项目源码 | 文件源码
def _load_bitmaps(self, metrics):

        #
        # bitmap data

        bitmaps = []

        fp, format, i16, i32 = self._getformat(PCF_BITMAPS)

        nbitmaps = i32(fp.read(4))

        if nbitmaps != len(metrics):
            raise IOError, "Wrong number of bitmaps"

        offsets = []
        for i in range(nbitmaps):
            offsets.append(i32(fp.read(4)))

        bitmapSizes = []
        for i in range(4):
            bitmapSizes.append(i32(fp.read(4)))

        byteorder = format & 4 # non-zero => MSB
        bitorder  = format & 8 # non-zero => MSB
        padindex  = format & 3

        bitmapsize = bitmapSizes[padindex]
        offsets.append(bitmapsize)

        data = fp.read(bitmapsize)

        pad  = BYTES_PER_ROW[padindex]
        mode = "1;R"
        if bitorder:
            mode = "1"

        for i in range(nbitmaps):
            x, y, l, r, w, a, d, f = metrics[i]
            b, e = offsets[i], offsets[i+1]
            bitmaps.append(
                Image.fromstring("1", (x, y), data[b:e], "raw", mode, pad(x))
                )

        return bitmaps
项目:InstagramPosting    作者:LeviParadis    | 项目源码 | 文件源码
def bdf_char(f):

    # skip to STARTCHAR
    while 1:
        s = f.readline()
        if not s:
            return None
        if s[:9] == "STARTCHAR":
            break
    id = string.strip(s[9:])

    # load symbol properties
    props = {}
    while 1:
        s = f.readline()
        if not s or s[:6] == "BITMAP":
            break
        i = string.find(s, " ")
        props[s[:i]] = s[i+1:-1]

    # load bitmap
    bitmap = []
    while 1:
        s = f.readline()
        if not s or s[:7] == "ENDCHAR":
            break
        bitmap.append(s[:-1])
    bitmap = string.join(bitmap, "")

    [x, y, l, d] = map(int, string.split(props["BBX"]))
    [dx, dy] = map(int, string.split(props["DWIDTH"]))

    bbox = (dx, dy), (l, -d-y, x+l, -d), (0, 0, x, y)

    try:
        im = Image.fromstring("1", (x, y), bitmap, "hex", "1")
    except ValueError:
        # deal with zero-width characters
        im = Image.new("1", (x, y))

    return id, int(props["ENCODING"]), bbox, im

##
# Font file plugin for the X11 BDF format.
项目:ngx_status    作者:YoYoAdorkable    | 项目源码 | 文件源码
def _load_bitmaps(self, metrics):

        #
        # bitmap data

        bitmaps = []

        fp, format, i16, i32 = self._getformat(PCF_BITMAPS)

        nbitmaps = i32(fp.read(4))

        if nbitmaps != len(metrics):
            raise IOError, "Wrong number of bitmaps"

        offsets = []
        for i in range(nbitmaps):
            offsets.append(i32(fp.read(4)))

        bitmapSizes = []
        for i in range(4):
            bitmapSizes.append(i32(fp.read(4)))

        byteorder = format & 4 # non-zero => MSB
        bitorder  = format & 8 # non-zero => MSB
        padindex  = format & 3

        bitmapsize = bitmapSizes[padindex]
        offsets.append(bitmapsize)

        data = fp.read(bitmapsize)

        pad  = BYTES_PER_ROW[padindex]
        mode = "1;R"
        if bitorder:
            mode = "1"

        for i in range(nbitmaps):
            x, y, l, r, w, a, d, f = metrics[i]
            b, e = offsets[i], offsets[i+1]
            bitmaps.append(
                Image.fromstring("1", (x, y), data[b:e], "raw", mode, pad(x))
                )

        return bitmaps
项目:ngx_status    作者:YoYoAdorkable    | 项目源码 | 文件源码
def bdf_char(f):

    # skip to STARTCHAR
    while 1:
        s = f.readline()
        if not s:
            return None
        if s[:9] == "STARTCHAR":
            break
    id = string.strip(s[9:])

    # load symbol properties
    props = {}
    while 1:
        s = f.readline()
        if not s or s[:6] == "BITMAP":
            break
        i = string.find(s, " ")
        props[s[:i]] = s[i+1:-1]

    # load bitmap
    bitmap = []
    while 1:
        s = f.readline()
        if not s or s[:7] == "ENDCHAR":
            break
        bitmap.append(s[:-1])
    bitmap = string.join(bitmap, "")

    [x, y, l, d] = map(int, string.split(props["BBX"]))
    [dx, dy] = map(int, string.split(props["DWIDTH"]))

    bbox = (dx, dy), (l, -d-y, x+l, -d), (0, 0, x, y)

    try:
        im = Image.fromstring("1", (x, y), bitmap, "hex", "1")
    except ValueError:
        # deal with zero-width characters
        im = Image.new("1", (x, y))

    return id, int(props["ENCODING"]), bbox, im

##
# Font file plugin for the X11 BDF format.