简体   繁体   中英

Using putpixel() doesn't write pixel values to image

I am using putpixel on an image ( srcImage ) which is w = 134 and h = 454.

The code here gets the r,g,b value of a part of the font which is 0,255,0 (which I found through debugging, using print option).

image = letters['H']  
r,g,b = image.getpixel((1,1)) #Note r g b values are 0, 255,0
srcImage.putpixel((10,15),(r,g,b))   
srcImage.save('lolmini2.jpg')

This code does not throw any error. However, when I check the saved image I cannot spot the pure green pixel.

Instead of using putpixel() and getpixel() you should use indexing instead. For getpixel() you can use pixesl[1, 1] and for putpixel you can use pixels[1, 1] = (r, g, b) . It should work the same but it's much faster. pixels here is image.load()

However, I don't see why it wouldn't work. It should work without a problem. Perhaps the jpeg compression is killing you here. Have you tried saving it as a png/gif file instead? Or setting more than 1 pixel.

I know it is a very old post but, for beginners who'd want to stick to putpixels() for a while, here's the solution:

initialize the image variable as:

from PIL import Image
img = Image.new('RGB', [200,200], 0x000000)

Make sure to initialize it as 'RGB' if you want to manipulate RGB values.

Sometimes people initialize images as:

img = Image.new('I', [200, 200], 0x000000)

and then try to work with RGB values, which doesn't work .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM