def ensure_same_mode(im1, im2): # if both images already have the same mode (and palette, in # case of mode P), don't convert anything. Images with mode P, # and a different palette, are the only case where images # using the same mode, will be incompatible with each other. if im1.mode == im2.mode and (im1.mode != 'P' or im1.getpalette() == im2.getpalette()): return (im1, im2) # if any given image has a mode that supports colors convert both # images to RGB or RGBA, otherwise convert both images to L or LA. # If any given image has an alpha channel (or mode P which # can store transparent pixels too) convert both images # to RGBA or LA, otherwise convert both images to RGB or L. mode = max(Image.getmodebase(im1.mode), Image.getmodebase(im2.mode), key=('L', 'RGB').index) if any(im.mode in ('RGBA', 'LA', 'P') for im in (im1, im2)): mode += 'A' return ( im1 if im1.mode == mode else im1.convert(mode), im2 if im2.mode == mode else im2.convert(mode), )
def ensure_same_mode(im1, im2): # if both images already have the same mode (and palette, in # case of mode P), don't convert anything. Images with mode P, # and a different palette, are the only case where images # using the same mode, will be incompatible with each other. if im1.mode == im2.mode and (im1.mode != 'P' or im1.getpalette() == im2.getpalette()): return (im1, im2) # if any given image has a mode that supports colors convert both # images to RGB or RGBA, otherwise convert both images to L or LA. # If any given image has an alpha channel (or mode P which # can store transparent pixels too) convert both images # to RGBA or LA, otherwise convert both images to RGB or L. mode = max( Image.getmodebase(im1.mode), Image.getmodebase(im2.mode), key=('L', 'RGB').index ) if any(im.mode in ('RGBA', 'LA', 'P') for im in (im1, im2)): mode += 'A' return ( im1 if im1.mode == mode else im1.convert(mode), im2 if im2.mode == mode else im2.convert(mode), )
def createPNG(self, filename=None): self.format = 'png' self.backend = 'eps' self.writeTemp(fp=filename) # do not need extension here lilyFile = self.runThroughLily() if noPIL is False: try: lilyImage = Image.open(lilyFile) lilyImage2 = ImageOps.expand(lilyImage, 10, 'white') if os.name == 'nt': format = 'png' # why are we changing format for darwin? -- did not work before elif sys.platform == 'darwin': format = 'jpeg' else: # default for all other platforms format = 'png' if lilyImage2.mode == "I;16": # @PIL88 @PIL101 # "I;16" isn't an 'official' mode, but we still want to # provide a simple way to show 16-bit images. base = "L" else: base = Image.getmodebase(lilyImage2.mode) if base != lilyImage2.mode and lilyImage2.mode != "1": file = lilyImage2.convert(base)._dump(format=format) else: file = lilyImage2._dump(format=format) return file except: raise return lilyFile
def getcolor(color, mode): """ Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to a greyscale value if the mode is not color or a palette image. If the string cannot be parsed, this function raises a :py:exc:`ValueError` exception. .. versionadded:: 1.1.4 :param color: A color string :return: ``(graylevel [, alpha]) or (red, green, blue[, alpha])`` """ # same as getrgb, but converts the result to the given mode color, alpha = getrgb(color), 255 if len(color) == 4: color, alpha = color[0:3], color[3] if Image.getmodebase(mode) == "L": r, g, b = color color = (r * 299 + g * 587 + b * 114) // 1000 if mode[-1] == 'A': return (color, alpha) else: if mode[-1] == 'A': return color + (alpha, ) return color
def __init__(self, image=None, size=None, **kw): # Tk compatibility: file or data if image is None: image = _get_image_from_kw(kw) if hasattr(image, "mode") and hasattr(image, "size"): # got an image instead of a mode mode = image.mode if mode == "P": # palette mapped data image.load() try: mode = image.palette.mode except AttributeError: mode = "RGB" # default size = image.size kw["width"], kw["height"] = size else: mode = image image = None if mode not in ["1", "L", "RGB", "RGBA"]: mode = Image.getmodebase(mode) self.__mode = mode self.__size = size self.__photo = tkinter.PhotoImage(**kw) self.tk = self.__photo.tk if image: self.paste(image)
def getcolor(color, mode): """ Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to a greyscale value if the mode is not color or a palette image. If the string cannot be parsed, this function raises a :py:exc:`ValueError` exception. .. versionadded:: 1.1.4 :param color: A color string :return: ``(graylevel [, alpha]) or (red, green, blue[, alpha])`` """ # same as getrgb, but converts the result to the given mode color, alpha = getrgb(color), 255 if len(color) == 4: color, alpha = color[0:3], color[3] if Image.getmodebase(mode) == "L": r, g, b = color color = (r*299 + g*587 + b*114)//1000 if mode[-1] == 'A': return (color, alpha) else: if mode[-1] == 'A': return color + (alpha,) return color
def check(mode, *result): signature = ( Image.getmodebase(mode), Image.getmodetype(mode), Image.getmodebands(mode), Image.getmodebandnames(mode), ) self.assertEqual(signature, result)
def check(mode, *result): signature = ( Image.getmodebase(mode), Image.getmodetype(mode), Image.getmodebands(mode), Image.getmodebandnames(mode), ) assert signature == result
def _convert_mode(im): # convert on the fly (EXPERIMENTAL -- I'm not sure PIL # should automatically convert images on save...) if Image.getmodebase(im.mode) == "RGB": palette_size = 256 if im.palette: palette_size = len(im.palette.getdata()[1]) // 3 return im.convert("P", palette=1, colors=palette_size) return im.convert("L")
def show(self, image, **options): # save temporary image to disk if not (image.mode in ("1", "RGBA") or (self.format == "PNG" and image.mode == "LA")): base = Image.getmodebase(image.mode) if image.mode != base: image = image.convert(base) return self.show_image(image, **options)
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 if im.mode in RAWMODE: im_out = im else: # convert on the fly (EXPERIMENTAL -- I'm not sure PIL # should automatically convert images on save...) if Image.getmodebase(im.mode) == "RGB": palette_size = 256 if im.palette: palette_size = len(im.palette.getdata()[1]) // 3 im_out = im.convert("P", palette=1, colors=palette_size) else: im_out = im.convert("L") # header try: palette = im.encoderinfo["palette"] except KeyError: palette = None im.encoderinfo["optimize"] = im.encoderinfo.get("optimize", True) header, used_palette_colors = getheader(im_out, palette, im.encoderinfo) for s in header: fp.write(s) flags = 0 if get_interlace(im): flags = flags | 64 # local image header get_local_header(fp, im, (0, 0), flags) im_out.encoderconfig = (8, get_interlace(im)) ImageFile._save(im_out, fp, [("gif", (0, 0)+im.size, 0, RAWMODE[im_out.mode])]) fp.write(b"\0") # end of image data fp.write(b";") # end of file try: fp.flush() except: pass
def getcolor(color, mode): # same as getrgb, but converts the result to the given mode color = getrgb(color) if mode == "RGB": return color if mode == "RGBA": r, g, b, a = color return r, g, b, a if Image.getmodebase(mode) == "L": r, g, b = color return (r * 299 + g * 587 + b * 114) // 1000 return color
def getcolor(color, mode): # same as getrgb, but converts the result to the given mode color = getrgb(color) if mode == "RGB": return color if mode == "RGBA": r, g, b = color return r, g, b, 255 if Image.getmodebase(mode) == "L": r, g, b = color return (r * 299 + g * 587 + b * 114) // 1000 return color
def show(self, image, **options): """ The main function for displaying an image. Converts the given image to the target format and displays it. """ if not (image.mode in ("1", "RGBA") or (self.format == "PNG" and image.mode in ("I;16", "LA"))): base = Image.getmodebase(image.mode) if image.mode != base: image = image.convert(base) return self.show_image(image, **options)
def __init__(self, image, size=None): if hasattr(image, "mode") and hasattr(image, "size"): mode = image.mode size = image.size else: mode = image image = None if mode not in ["1", "L", "P", "RGB"]: mode = Image.getmodebase(mode) self.image = Image.core.display(mode, size) self.mode = mode self.size = size if image: self.paste(image)
def show(self, image, **options): # save temporary image to disk if image.mode[:4] == "I;16": # @PIL88 @PIL101 # "I;16" isn't an 'official' mode, but we still want to # provide a simple way to show 16-bit images. base = "L" # FIXME: auto-contrast if max() > 255? else: base = Image.getmodebase(image.mode) if base != image.mode and image.mode != "1" and image.mode != "RGBA": image = image.convert(base) return self.show_image(image, **options)
def showPNG(self): '''Take the LilyString, run it through LilyPond, and then show it as a PNG file. On Windows, the PNG file will not be deleted, so you will need to clean out TEMP every once in a while ''' self.format = 'png' self.backend = 'eps' self.writeTemp() # do not need extension here lilyFile = self.runThroughLily() if noPIL is False: try: lilyImage = Image.open(lilyFile) lilyImage2 = ImageOps.expand(lilyImage, 10, 'white') if os.name == 'nt': format = 'png' # why are we changing format for darwin? elif sys.platform == 'darwin': format = 'jpeg' else: # default for all other platforms format = 'png' if lilyImage2.mode == "I;16": # @PIL88 @PIL101 # "I;16" isn't an 'official' mode, but we still want to # provide a simple way to show 16-bit images. base = "L" else: base = Image.getmodebase(lilyImage2.mode) if base != lilyImage2.mode and lilyImage2.mode != "1": file = lilyImage2.convert(base)._dump(format=format) else: file = lilyImage2._dump(format=format) environLocal.launch(format.lower(), file) #self.showImageDirect(file) except: raise # this will never execute after an extension #self.showImageDirect(lilyFile) else: environLocal.launch(self.format.lower(), lilyFile) #self.showImageDirect(lilyFile) return lilyFile
def __init__(self, image): args = ['pngout', '-', '-', '-q'] # Preserve mode for grayscale images. pngout tends to convert # everyting to palette. However, the toolbar icons for Safari # require the grayscale+alpha mode. Moreover, pngout seems to # generate smaller files when forced to preserve grayscale mode. if image.mode == 'LA' and any(px < 0xff for px in image.split()[1].getdata()): args.append('-c4') # grayscale+alpha elif Image.getmodebase(image.mode) == 'L': args.append('-c0') # grayscale self._pngout = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) # Writing will block when the buffer is full until we read more data # from the output. Reading the output will block when the input isn't # complete yet. So we have to use threads to do both at the same time. self._thread = threading.Thread(target=self._run_thread, args=(image,)) self._thread.daemon = True self._thread.start()
def _decode_alpha(self, frame, info): alpha_size = si32le(self.fd.read(4)) packed_data = zlib.decompress(self.fd.read(alpha_size)) unpacked = self._unpack_layer( BytesIO(packed_data), frame, info["block_width"], info["block_height"], info["randomized"], info["frames"], True, ) size = self.state.xsize, self.state.ysize mask = Image.frombytes("L", size, unpacked, "raw", "L", frame["alpha_stride"]) if Image.getmodebase(self.mode) == "RGB": band = 3 else: band = 1 self.im.putband(mask.im, band)
def showPNG(self): '''Take the LilyString, run it through LilyPond, and then show it as a PNG file. On Windows, the PNG file will not be deleted, so you will need to clean out TEMP every once in a while ''' self.format = 'png' self.backend = 'eps' self.writeTemp() lilyFile = self.runThroughLily() if noPIL is False: try: lilyImage = Image.open(lilyFile) lilyImage2 = ImageOps.expand(lilyImage, 10, "white") if os.name == "nt": format = "PNG" elif sys.platform == "darwin": format = "JPEG" else: format = None if lilyImage2.mode == "I;16": # @PIL88 @PIL101 # "I;16" isn't an 'official' mode, but we still want to # provide a simple way to show 16-bit images. base = "L" else: base = Image.getmodebase(lilyImage2.mode) if base != lilyImage2.mode and lilyImage2.mode != "1": file = lilyImage2.convert(base)._dump(format=format) else: file = lilyImage2._dump(format=format) self.showImageDirect(file) except: raise self.showImageDirect(lilyFile) else: self.showImageDirect(lilyFile) return lilyFile
def __init__(self, image=None, size=None, **kw): # Tk compatibility: file or data if image is None: if kw.has_key("file"): image = Image.open(kw["file"]) del kw["file"] elif kw.has_key("data"): from StringIO import StringIO image = Image.open(StringIO(kw["data"])) del kw["data"] if hasattr(image, "mode") and hasattr(image, "size"): # got an image instead of a mode mode = image.mode if mode == "P": # palette mapped data image.load() try: mode = image.palette.mode except AttributeError: mode = "RGB" # default size = image.size kw["width"], kw["height"] = size else: mode = image image = None if mode not in ["1", "L", "RGB", "RGBA"]: mode = Image.getmodebase(mode) self.__mode = mode self.__size = size self.__photo = apply(Tkinter.PhotoImage, (), kw) self.tk = self.__photo.tk if image: self.paste(image)
def getcolor(color, mode): """ Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to a greyscale value if the mode is not color or a palette image. If the string cannot be parsed, this function raises a :py:exc:`ValueError` exception. .. versionadded:: 1.1.4 :param color: A color string :return: ``(red, green, blue)`` """ # same as getrgb, but converts the result to the given mode color = getrgb(color) if mode == "RGB": return color if mode == "RGBA": if len(color) == 3: color = (color + (255,)) r, g, b, a = color return r, g, b, a if Image.getmodebase(mode) == "L": r, g, b = color return (r*299 + g*587 + b*114)//1000 return color
def getcolor(color, mode): """ Same as :py:func:`~PIL.ImageColor.getrgb`, but converts the RGB value to a greyscale value if the mode is not color or a palette image. If the string cannot be parsed, this function raises a :py:exc:`ValueError` exception. .. versionadded:: 1.1.4 :param color: A color string :return: ``(red, green, blue)`` """ # same as getrgb, but converts the result to the given mode color = getrgb(color) if mode == "RGB": return color if mode == "RGBA": if len(color) == 3: color = (color + (255, )) r, g, b, a = color return r, g, b, a if Image.getmodebase(mode) == "L": r, g, b = color return (r * 299 + g * 587 + b * 114) // 1000 return color
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 try: palette = im.encoderinfo["palette"] except KeyError: palette = None if im.palette: # use existing if possible palette = im.palette.getdata()[1] header, usedPaletteColors = getheader(imOut, palette, im.encoderinfo) for s in header: fp.write(s) flags = 0 try: interlace = im.encoderinfo["interlace"] except KeyError: interlace = 1 # workaround for @PIL153 if min(im.size) < 16: interlace = 0 if interlace: flags = flags | 64 try: transparency = im.encoderinfo["transparency"] except KeyError: pass else: transparency = int(transparency) # optimize the block away if transparent color is not used transparentColorExists = True # adjust the transparency index after optimize if usedPaletteColors is not None and len(usedPaletteColors) < 256: for i in range(len(usedPaletteColors)): if usedPaletteColors[i] == transparency: transparency = i transparentColorExists = True break else: transparentColorExists = False # transparency extension block if transparentColorExists: fp.write( b"!" + o8(249) + o8(4) # extension intro + o8(1) # length + o16(0) # transparency info present + o8(transparency) # duration # transparency index + o8(0) ) # local image header fp.write( b"," + o16(0) + o16(0) + o16(im.size[0]) + o16(im.size[1]) + o8(flags) + o8(8) # bounding box # size # flags ) # bits imOut.encoderconfig = (8, interlace) ImageFile._save(imOut, fp, [("gif", (0, 0) + im.size, 0, rawmode)]) fp.write(b"\0") # end of image data fp.write(b";") # end of file try: fp.flush() except: pass
def verify_bw(img): img = remove_transparency(img) if Image.getmodebase(img.mode) == 'L': return img else: return convert2mono(img)
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": palette_size = 256 if im.palette: palette_size = len(im.palette.getdata()[1]) // 3 imOut = im.convert("P", palette=1, colors=palette_size) rawmode = "P" else: imOut = im.convert("L") rawmode = "L" # header try: palette = im.encoderinfo["palette"] except KeyError: palette = None im.encoderinfo["optimize"] = im.encoderinfo.get("optimize", True) if im.encoderinfo["optimize"]: # When the mode is L, and we optimize, we end up with # im.mode == P and rawmode = L, which fails. # If we're optimizing the palette, we're going to be # in a rawmode of P anyway. rawmode = 'P' header, usedPaletteColors = getheader(imOut, palette, im.encoderinfo) for s in header: fp.write(s) flags = 0 try: interlace = im.encoderinfo["interlace"] except KeyError: interlace = 1 # workaround for @PIL153 if min(im.size) < 16: interlace = 0 if interlace: flags = flags | 64 try: transparency = im.encoderinfo["transparency"] except KeyError: pass else: transparency = int(transparency) # optimize the block away if transparent color is not used transparentColorExists = True # adjust the transparency index after optimize if usedPaletteColors is not None and len(usedPaletteColors) < 256: for i in range(len(usedPaletteColors)): if usedPaletteColors[i] == transparency: transparency = i transparentColorExists = True break else: transparentColorExists = False # transparency extension block if transparentColorExists: fp.write(b"!" + o8(249) + # extension intro o8(4) + # length o8(1) + # transparency info present o16(0) + # duration o8(transparency) # transparency index + o8(0)) # local image header fp.write(b"," + o16(0) + o16(0) + # bounding box o16(im.size[0]) + # size o16(im.size[1]) + o8(flags) + # flags o8(8)) # bits imOut.encoderconfig = (8, interlace) ImageFile._save(imOut, fp, [("gif", (0,0)+im.size, 0, rawmode)]) fp.write(b"\0") # end of image data fp.write(b";") # end of file try: fp.flush() except: pass
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 try: palette = im.encoderinfo["palette"] except KeyError: palette = None header, usedPaletteColors = getheader(imOut, palette, im.encoderinfo) for s in header: fp.write(s) flags = 0 try: interlace = im.encoderinfo["interlace"] except KeyError: interlace = 1 # workaround for @PIL153 if min(im.size) < 16: interlace = 0 if interlace: flags = flags | 64 try: transparency = im.encoderinfo["transparency"] except KeyError: pass else: transparency = int(transparency) # optimize the block away if transparent color is not used transparentColorExists = True # adjust the transparency index after optimize if usedPaletteColors is not None and len(usedPaletteColors) < 256: for i in range(len(usedPaletteColors)): if usedPaletteColors[i] == transparency: transparency = i transparentColorExists = True break else: transparentColorExists = False # transparency extension block if transparentColorExists: fp.write(b"!" + o8(249) + # extension intro o8(4) + # length o8(1) + # transparency info present o16(0) + # duration o8(transparency) # transparency index + o8(0)) # local image header fp.write(b"," + o16(0) + o16(0) + # bounding box o16(im.size[0]) + # size o16(im.size[1]) + o8(flags) + # flags o8(8)) # bits imOut.encoderconfig = (8, interlace) ImageFile._save(imOut, fp, [("gif", (0, 0) + im.size, 0, rawmode)]) fp.write(b"\0") # end of image data fp.write(b";") # end of file try: fp.flush() except: pass
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 KeyError: interlace = 1 # workaround for @PIL153 if min(im.size) < 16: interlace = 0 if interlace: flags = flags | 64 try: transparency = im.encoderinfo["transparency"] except KeyError: pass else: # transparency extension block fp.write("!" + chr(249) + # extension intro chr(4) + # length chr(1) + # transparency info present o16(0) + # duration chr(int(transparency)) # transparency index + chr(0)) # local image header fp.write("," + o16(0) + o16(0) + # bounding box o16(im.size[0]) + # size o16(im.size[1]) + chr(flags) + # flags chr(8)) # 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