This commit is contained in:
amoibos 2014-05-09 16:11:00 +00:00
commit 8f47e5c619
20 changed files with 50 additions and 77 deletions

View File

@ -133,7 +133,7 @@ class BmpImageFile(ImageFile.ImageFile):
greyscale = 1
if colors == 2:
indices = (0, 255)
elif colors > 2**16 or colors <=0: #We're reading a i32.
elif not 0 < colors <= 2**16: #We're reading a i32.
raise IOError("Unsupported BMP Palette size (%d)" % colors)
else:
indices = list(range(colors))
@ -232,8 +232,7 @@ def _save(im, fp, filename, check=0):
for i in (0, 255):
fp.write(o8(i) * 4)
elif im.mode == "L":
for i in range(256):
fp.write(o8(i) * 4)
fp.write("".join(o8(i) * 4 for i in range(256)))
elif im.mode == "P":
fp.write(im.im.getpalette("RGB", "BGRX"))

View File

@ -102,7 +102,7 @@ class IcoFile:
Get an image from the icon
"""
for (i, h) in enumerate(self.entry):
if size == h['dim'] and (bpp == False or bpp == h['color_depth']):
if size == h['dim'] and bpp in (h['color_depth'], False):
return self.frame(i)
return self.frame(0)

View File

@ -134,7 +134,7 @@ class ImImageFile(ImageFile.ImageFile):
if s == b"\r":
continue
if not s or s == b'\0' or s == b'\x1A':
if not s or s in (b'\0', b'\x1A'):
break
# FIXME: this may read whole file if not a text file
@ -212,7 +212,7 @@ class ImImageFile(ImageFile.ImageFile):
linear = 0
else:
greyscale = 0
if self.mode == "L" or self.mode == "LA":
if self.mode in ("L", "LA"):
if greyscale:
if not linear:
self.lut = [i8(c) for c in palette[:256]]
@ -258,7 +258,7 @@ class ImImageFile(ImageFile.ImageFile):
def seek(self, frame):
if frame < 0 or frame >= self.info[FRAMES]:
if not 0 <= frame < self.info[FRAMES]:
raise EOFError("seek outside sequence")
if self.frame == frame:

View File

@ -233,7 +233,7 @@ _MODE_CONV = {
"CMYK": ('|u1', 4),
"YCbCr": ('|u1', 3),
"LAB": ('|u1', 3), # UNDONE - unsigned |u1i1i1
# I;16 == I;16L, and I;32 == I;32L
# I;16 == I;16L, and I;32 == I;32L
"I;16": ('<u2', None),
"I;16B": ('>u2', None),
"I;16L": ('<u2', None),
@ -918,10 +918,10 @@ class Image:
:returns: An :py:class:`~PIL.Image.Image` object.
"""
self.load()
if box is None:
return self.copy()
else:
self.load()
# lazy operation
return _ImageCrop(self, box)

View File

@ -86,7 +86,7 @@ def autocontrast(image, cutoff=0, ignore=None):
# get number of pixels
n = 0
for ix in range(256):
n = n + h[ix]
n += h[ix]
# remove cutoff% pixels from the low end
cut = n * cutoff // 100
for lo in range(256):
@ -147,13 +147,10 @@ def colorize(image, black, white):
assert image.mode == "L"
black = _color(black, "RGB")
white = _color(white, "RGB")
red = []; green = []; blue = []
for i in range(256):
red.append(black[0]+i*(white[0]-black[0])//255)
green.append(black[1]+i*(white[1]-black[1])//255)
blue.append(black[2]+i*(white[2]-black[2])//255)
image = image.convert("RGB")
return _lut(image, red + green + blue)
return _lut(image, ([black[0]+i*(white[0]-black[0])//255 for i in range(256)] +
[black[1]+i*(white[1]-black[1])//255 for i in range(256)] +
[black[2]+i*(white[2]-black[2])//255 for i in range(256)]))
def crop(image, border=0):
@ -272,12 +269,12 @@ def fit(image, size, method=Image.NEAREST, bleed=0.0, centering=(0.5, 0.5)):
if not isinstance(centering, list):
centering = [centering[0], centering[1]]
if centering[0] > 1.0 or centering[0] < 0.0:
if not 0.0 < centering[0] < 1.0:
centering [0] = 0.50
if centering[1] > 1.0 or centering[1] < 0.0:
if not 0.0 < centering[1] < 1.0:
centering[1] = 0.50
if bleed > 0.49999 or bleed < 0.0:
if not 0.0 < bleed < 0.49999:
bleed = 0.0
# calculate the area to use for resizing and cropping, subtracting
@ -357,10 +354,7 @@ def invert(image):
:param image: The image to invert.
:return: An image.
"""
lut = []
for i in range(256):
lut.append(255-i)
return _lut(image, lut)
return _lut(image, [255 - i for i in range(256)])
def mirror(image):
@ -381,11 +375,8 @@ def posterize(image, bits):
:param bits: The number of bits to keep for each channel (1-8).
:return: An image.
"""
lut = []
mask = ~(2**(8-bits)-1)
for i in range(256):
lut.append(i & mask)
return _lut(image, lut)
return _lut(image, [i & mask for i in range(256)])
def solarize(image, threshold=128):
@ -396,13 +387,7 @@ def solarize(image, threshold=128):
:param threshold: All pixels above this greyscale level are inverted.
:return: An image.
"""
lut = []
for i in range(256):
if i < threshold:
lut.append(i)
else:
lut.append(255-i)
return _lut(image, lut)
return _lut(image, [i if i < threshold else 255 - i for i in range(256)])
# --------------------------------------------------------------------
# PIL USM components, from Kevin Cazabon.

View File

@ -20,7 +20,7 @@ import array
from PIL import Image, ImageColor
class ImagePalette:
class ImagePalette(object):
"Color palette for palette mapped images"
def __init__(self, mode = "RGB", palette = None, size = 0):
@ -120,19 +120,12 @@ def raw(rawmode, data):
# Factories
def _make_linear_lut(black, white):
lut = []
if black == 0:
for i in range(256):
lut.append(white*i//255)
else:
if black != 0:
raise NotImplementedError # FIXME
return lut
return [(white*i//255) for i in range(256)]
def _make_gamma_lut(exp, mode="RGB"):
lut = []
for i in range(256):
lut.append(int(((i / 255.0) ** exp) * 255.0 + 0.5))
return lut
return [int(((i / 255.0) ** exp) * 255.0 + 0.5) for i in range(256)]
def new(mode, data):
return Image.core.new_palette(mode, data)
@ -144,10 +137,8 @@ def negative(mode="RGB"):
def random(mode="RGB"):
from random import randint
palette = []
for i in range(256*len(mode)):
palette.append(randint(0, 255))
return ImagePalette(mode, palette)
return ImagePalette(mode, [randint(0, 255) for i in range(256 * len(mode))])
def sepia(white="#fff0c0"):
r, g, b = ImageColor.getrgb(white)

View File

@ -20,7 +20,7 @@ from PIL import Image
# the Python class below is overridden by the C implementation.
class Path:
class Path(object):
def __init__(self, xy):
pass

View File

@ -30,7 +30,7 @@ except:
def rgb(r, g, b, a=255):
# use qRgb to pack the colors, and then turn the resulting long
# into a negative integer with the same bitpattern.
return (qRgba(r, g, b, a) & 0xffffffff)
return qRgba(r, g, b, a) & 0xffffffff
##
# An PIL image wrapper for Qt. This is a subclass of PyQt4's QImage
@ -57,9 +57,7 @@ class ImageQt(QImage):
format = QImage.Format_Mono
elif im.mode == "L":
format = QImage.Format_Indexed8
colortable = []
for i in range(256):
colortable.append(rgb(i, i, i))
colortable = [rgb(i, i, i) for i in range(256)]
elif im.mode == "P":
format = QImage.Format_Indexed8
colortable = []

View File

@ -15,7 +15,7 @@
##
class Iterator:
class Iterator(object):
"""
This class implements an iterator object that can be used to loop
over an image sequence.

View File

@ -17,7 +17,7 @@ from __future__ import print_function
from PIL import Image
import os, sys
if(sys.version_info >= (3, 3)):
if sys.version_info >= (3, 3):
from shlex import quote
else:
from pipes import quote
@ -52,7 +52,7 @@ def show(image, title=None, **options):
##
# Base class for viewers.
class Viewer:
class Viewer(object):
# main api

View File

@ -26,7 +26,7 @@ import operator, math
from functools import reduce
class Stat:
class Stat(object):
def __init__(self, image_or_list, mask = None):
try:

View File

@ -54,7 +54,7 @@ def _pilbitmap_check():
# --------------------------------------------------------------------
# PhotoImage
class PhotoImage:
class PhotoImage(object):
"""
A Tkinter-compatible photo image. This can be used
everywhere Tkinter expects an image object. If the image is an RGBA
@ -192,7 +192,7 @@ class PhotoImage:
# BitmapImage
class BitmapImage:
class BitmapImage(object):
"""
A Tkinter-compatible bitmap image. This can be used everywhere Tkinter

View File

@ -21,7 +21,7 @@ import warnings
from PIL import Image
class HDC:
class HDC(object):
"""
Wraps a HDC integer. The resulting object can be passed to the
:py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
@ -32,7 +32,7 @@ class HDC:
def __int__(self):
return self.dc
class HWND:
class HWND(object):
"""
Wraps a HWND integer. The resulting object can be passed to the
:py:meth:`~PIL.ImageWin.Dib.draw` and :py:meth:`~PIL.ImageWin.Dib.expose`
@ -44,7 +44,7 @@ class HWND:
return self.wnd
class Dib:
class Dib(object):
"""
A Windows bitmap with the given mode and size. The mode can be one of "1",
"L", "P", or "RGB".
@ -207,7 +207,7 @@ class Dib:
##
# Create a Window with the given title size.
class Window:
class Window(object):
def __init__(self, title="PIL", width=None, height=None):
self.hwnd = Image.core.createwindow(

View File

@ -68,7 +68,7 @@ class IptcImageFile(ImageFile.ImageFile):
tag = i8(s[1]), i8(s[2])
# syntax
if i8(s[0]) != 0x1C or tag[0] < 1 or tag[0] > 9:
if i8(s[0]) != 0x1C or not 1 <= tag[0] <= 9:
raise SyntaxError("invalid IPTC/NAA file")
# field size

View File

@ -307,7 +307,7 @@ class JpegImageFile(ImageFile.ImageFile):
# self.__offset = self.fp.tell()
break
s = self.fp.read(1)
elif i == 0 or i == 65535:
elif i in (0, 65535):
# padded marker or junk; move on
s = "\xff"
else:

View File

@ -699,7 +699,7 @@ class _OleStream(io.BytesIO):
debug('sect=ENDOFCHAIN before expected size')
raise IOError('incomplete OLE stream')
# sector index should be within FAT:
if sect<0 or sect>=len(fat):
if not 0 <= sect < len(fat):
debug('sect=%d (%X) / len(fat)=%d' % (sect, sect, len(fat)))
debug('i=%d / nb_sectors=%d' %(i, nb_sectors))
## tmp_data = b"".join(data)
@ -920,7 +920,7 @@ class _OleDirectoryEntry:
if child_sid == NOSTREAM:
return
# check if child SID is in the proper range:
if child_sid<0 or child_sid>=len(self.olefile.direntries):
if not 0 <= child_sid < len(self.olefile.direntries):
self.olefile._raise_defect(DEFECT_FATAL, 'OLE DirEntry index out of range')
# get child direntry:
child = self.olefile._load_direntry(child_sid) #direntries[child_sid]
@ -1385,7 +1385,7 @@ class OleFileIO:
# The FAT is a sector chain starting at the first index of itself.
for isect in fat1:
#print("isect = %X" % isect)
if isect == ENDOFCHAIN or isect == FREESECT:
if isect in (ENDOFCHAIN, FREESECT):
# the end of the sector chain has been reached
break
# read the FAT sector
@ -1572,7 +1572,7 @@ class OleFileIO:
raise: IOError if the entry has always been referenced.
"""
# check if SID is OK:
if sid<0 or sid>=len(self.direntries):
if 0 <= sid < len(self.direntries):
self._raise_defect(DEFECT_FATAL, "OLE directory index out of range")
# check if entry was already referenced:
if self.direntries[sid] is not None:

View File

@ -173,8 +173,7 @@ def _save(im, fp, filename, check=0):
elif im.mode == "L":
# greyscale palette
fp.write(o8(12))
for i in range(256):
fp.write(o8(i)*3)
fp.write("".join(o8(i)*3 for i in range(256)))
# --------------------------------------------------------------------
# registry

View File

@ -555,8 +555,9 @@ def _save(im, fp, filename, chunk=putchunk, check=0):
if im.mode == "P":
palette_byte_number = (2 ** bits) * 3
palette_bytes = im.im.getpalette("RGB")[:palette_byte_number]
while len(palette_bytes) < palette_byte_number:
palette_bytes += b'\0'
diff = palette_byte_number - len(palette_bytes)
if diff > 0:
palette_bytes += b'\0' * diff
chunk(fp, b"PLTE", palette_bytes)
transparency = im.encoderinfo.get('transparency',im.info.get('transparency', None))

View File

@ -53,7 +53,7 @@ class SgiImageFile(ImageFile.ImageFile):
layout = i8(s[3]), i16(s[4:]), i16(s[10:])
# determine mode from bytes/zsize
if layout == (1, 2, 1) or layout == (1, 1, 1):
if layout in ((1, 2, 1), (1, 1, 1)):
self.mode = "L"
elif layout == (1, 3, 3):
self.mode = "RGB"

View File

@ -1043,7 +1043,7 @@ def _save(im, fp, filename):
unit = im.encoderinfo["resolution unit"]
if unit == "inch":
ifd[RESOLUTION_UNIT] = 2
elif unit == "cm" or unit == "centimeter":
elif unit in ("cm", "centimeter"):
ifd[RESOLUTION_UNIT] = 3
else:
ifd[RESOLUTION_UNIT] = 1