2010-08-29 40 views

Trả lời

20

Để xây dựng dựa trên ví dụ được đưa ra trong Gabi Purcaru link, đây là thứ được ghép với nhau từ PIL docs.

Cách đơn giản nhất để chắc chắn sửa đổi một pixel sử dụng PIL sẽ là:

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") 

Điều đó sẽ làm việc trong PIL 1.1.6 trở lên. Nếu bạn có may mắn khi phải hỗ trợ một phiên bản cũ hơn, bạn có thể hy sinh hiệu suất và thay thế pix[x, y] = value bằng im.putpixel((x, y), value).

+5

+1 cho 'NotImplementedError' – heltonbiker

Các vấn đề liên quan