我们从Python开源项目中,提取了以下30个代码示例,用于说明如何使用Image.Image()。
def _import_image(img): try: try: import Image as PILImage except ImportError: from PIL import Image as PILImage except ImportError: raise ImportError('You must install PIL to fetch image objects') if not isinstance(img, PILImage.Image): img = PILImage.open(img) return img
def import_zlib(): try: import zlib except ImportError: zlib = None from reportlab.rl_config import ZLIB_WARNINGS if ZLIB_WARNINGS: warnOnce('zlib not available') return zlib # Image Capability Detection. Set a flag haveImages # to tell us if either PIL or Java imaging libraries present. # define PIL_Image as either None, or an alias for the PIL.Image # module, as there are 2 ways to import it
def _isPILImage(im): try: return isinstance(im,Image.Image) except AttributeError: return 0
def _read_image(self,fp): if sys.platform[0:4] == 'java': from javax.imageio import ImageIO return ImageIO.read(fp) else: return Image.open(fp)
def image_entropy(im): """ Calculate the entropy of an image. Used for "smart cropping". """ if not isinstance(im, Image.Image): # Can only deal with PIL images. Fall back to a constant entropy. return 0 hist = im.histogram() hist_size = float(sum(hist)) hist = [h / hist_size for h in hist] return -sum([p * math.log(p, 2) for p in hist if p != 0])
def is_transparent(image): """ Check to see if an image is transparent. """ if not isinstance(image, Image.Image): # Can only deal with PIL images, fall back to the assumption that that # it's not transparent. return False return (image.mode in ('RGBA', 'LA') or (image.mode == 'P' and 'transparency' in image.info))
def is_progressive(image): """ Check to see if an image is progressive. """ if not isinstance(image, Image.Image): # Can only check PIL images for progressive encoding. return False return ('progressive' in image.info) or ('progression' in image.info)
def exif_orientation(im): """ Rotate and/or flip an image to respect the image's EXIF orientation data. """ try: exif = im._getexif() except Exception: # There are many ways that _getexif fails, we're just going to blanket # cover them all. exif = None if exif: orientation = exif.get(0x0112) if orientation == 2: im = im.transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 3: im = im.rotate(180) elif orientation == 4: im = im.transpose(Image.FLIP_TOP_BOTTOM) elif orientation == 5: im = im.rotate(-90).transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 6: im = im.rotate(-90) elif orientation == 7: im = im.rotate(90).transpose(Image.FLIP_LEFT_RIGHT) elif orientation == 8: im = im.rotate(90) return im
def raise_ioerror(error): try: message = Image.core.getcodecstatus(error) except AttributeError: message = ERRORS.get(error) if not message: message = "decoder error %d" % error raise IOError(message + " when reading image file") # # -------------------------------------------------------------------- # Helpers
def __init__(self, fp=None, filename=None): Image.Image.__init__(self) self.tile = None self.readonly = 1 # until we know better self.decoderconfig = () self.decodermaxblock = MAXBLOCK if Image.isStringType(fp): # filename self.fp = open(fp, "rb") self.filename = fp else: # stream self.fp = fp self.filename = filename try: self._open() except IndexError, v: # end of data if Image.DEBUG > 1: traceback.print_exc() raise SyntaxError, v except TypeError, v: # end of data (ord) if Image.DEBUG > 1: traceback.print_exc() raise SyntaxError, v except KeyError, v: # unsupported mode if Image.DEBUG > 1: traceback.print_exc() raise SyntaxError, v except EOFError, v: # got header but not the first frame if Image.DEBUG > 1: traceback.print_exc() raise SyntaxError, v if not self.mode or self.size[0] <= 0: raise SyntaxError, "not identified by this driver"
def load_prepare(self): # create image memory if necessary if not self.im or\ self.im.mode != self.mode or self.im.size != self.size: self.im = Image.core.new(self.mode, self.size) # create palette (optional) if self.mode == "P": Image.Image.load(self)
def seek(self, offset, whence=0): if whence == 0: self.offset = offset elif whence == 1: self.offset = self.offset + offset else: # force error in Image.open raise IOError("illegal argument to seek")
def close(self): # finish decoding if self.decoder: # get rid of what's left in the buffers self.feed("") self.data = self.decoder = None if not self.finished: raise IOError("image was incomplete") if not self.image: raise IOError("cannot parse this image") if self.data: # incremental parsing not possible; reopen the file # not that we have all data try: fp = _ParserFile(self.data) self.image = Image.open(fp) finally: self.image.load() fp.close() # explicitly close the virtual file return self.image # -------------------------------------------------------------------- ## # (Helper) Save image body to file. # # @param im Image object. # @param fp File object. # @param tile Tile list.
def close(self): # finish decoding if self.decoder: # get rid of what's left in the buffers self.feed("") self.data = self.decoder = None if not self.finished: raise IOError("image was incomplete") if not self.image: raise IOError("cannot parse this image") if self.data: # incremental parsing not possible; reopen the file # not that we have all data try: fp = _ParserFile(self.data) self.image = Image.open(fp) finally: fp.close() # explicitly close the virtual file return self.image # -------------------------------------------------------------------- ## # (Helper) Save image body to file. # # @param im Image object. # @param fp File object. # @param tile Tile list.
def getRGBData(self): "Return byte array of RGB data as string" try: if self._data is None: self._dataA = None if sys.platform[0:4] == 'java': import jarray from java.awt.image import PixelGrabber width, height = self.getSize() buffer = jarray.zeros(width*height, 'i') pg = PixelGrabber(self._image, 0,0,width,height,buffer,0,width) pg.grabPixels() # there must be a way to do this with a cast not a byte-level loop, # I just haven't found it yet... pixels = [] a = pixels.append for i in range(len(buffer)): rgb = buffer[i] a(chr((rgb>>16)&0xff)) a(chr((rgb>>8)&0xff)) a(chr(rgb&0xff)) self._data = ''.join(pixels) self.mode = 'RGB' else: im = self._image mode = self.mode = im.mode if mode=='RGBA': if Image.VERSION.startswith('1.1.7'): im.load() self._dataA = ImageReader(im.split()[3]) im = im.convert('RGB') self.mode = 'RGB' elif mode not in ('L','RGB','CMYK'): if im.format=='PNG' and im.mode=='P' and 'transparency' in im.info: im = im.convert('RGBA') self._dataA = ImageReader(im.split()[3]) im = im.convert('RGB') else: im = im.convert('RGB') self.mode = 'RGB' self._data = (im.tobytes if hasattr(im, 'tobytes') else im.tostring)() #make pillow and PIL both happy, for now return self._data except: annotateException('\nidentity=%s'%self.identity())
def _save(im, fp, tile): "Helper to save image based on tile list" im.load() if not hasattr(im, "encoderconfig"): im.encoderconfig = () tile.sort(_tilesort) # FIXME: make MAXBLOCK a configuration parameter bufsize = max(MAXBLOCK, im.size[0] * 4) # see RawEncode.c try: fh = fp.fileno() fp.flush() except AttributeError: # compress to Python file-compatible object for e, b, o, a in tile: e = Image._getencoder(im.mode, e, a, im.encoderconfig) if o > 0: fp.seek(o, 0) e.setimage(im.im, b) while 1: l, s, d = e.encode(bufsize) fp.write(d) if s: break if s < 0: raise IOError("encoder error %d when writing image file" % s) else: # slight speedup: compress to real file object for e, b, o, a in tile: e = Image._getencoder(im.mode, e, a, im.encoderconfig) if o > 0: fp.seek(o, 0) e.setimage(im.im, b) s = e.encode_to_file(fh, bufsize) if s < 0: raise IOError("encoder error %d when writing image file" % s) try: fp.flush() except: pass ## # Reads large blocks in a safe way. Unlike fp.read(n), this function # doesn't trust the user. If the requested size is larger than # SAFEBLOCK, the file is read block by block. # # @param fp File handle. Must implement a <b>read</b> method. # @param size Number of bytes to read. # @return A string containing up to <i>size</i> bytes of data.