2010-08-29 29 views

回答

20

要以Gabi Purcaru的link中给出的示例为基础,请从PIL docs拼凑一些东西。

最简单的方法来使用PIL将可靠地修改单个像素:

x, y = 10, 25 
shade = 20 

from PIL import Image 
im = Image.open("foo.png") 
pix = im.load() 

if im.mode == '1': 
    value = int(shade >= 127) # Black-and-white (1-bit) 
elif im.mode == 'L': 
    value = shade # Grayscale (Luminosity) 
elif im.mode == 'RGB': 
    value = (shade, shade, shade) 
elif im.mode == 'RGBA': 
    value = (shade, shade, shade, 255) 
elif im.mode == 'P': 
    raise NotImplementedError("TODO: Look up nearest color in palette") 
else: 
    raise ValueError("Unexpected mode for PNG image: %s" % im.mode) 

pix[x, y] = value 

im.save("foo_new.png") 

这将在PIL 1.1.6和后续工作。如果您不幸支持旧版本,则可能会牺牲性能,并用im.putpixel((x, y), value)替换pix[x, y] = value

+5

+1对于'NotImplementedError' – heltonbiker 2011-09-28 16:19:44

相关问题