how can change 24 bit depth to 8 bit depth in python in pillow?

Viewed 654

i have a 1.png and it is 24 bit depth.i want to convert it to 8 bit depth with python with pillow.

I tried this code but when i have checked both of these images(1.png and 2.png) were still 24 bit depth:

from PIL import Image
import os
os.chdir('D:\\test')
img=Image.open('1.png')
img.convert("P", palette=Image.ADAPTIVE, colors=8)
img.save('D:\\test\\2.png')
 

images : images

How can i convert my 1.png to an 8 bit depth and save it in pillow?

2 Answers

I solved my problem but i don't know why previous code did not worked!

I added img.convert("P", palette=Image.ADAPTIVE, colors=8) to a new variable. and saved it with a.save('D:\\test\\2.png')

from PIL import Image
import os
os.chdir('D:\\hash lip\\test')
img=Image.open('1.png')
a=img.convert("P", palette=Image.ADAPTIVE, colors=8)
a.save('D:\\test\\2.png')
 

convert() doesn't change original image in img but it creates new image which you have to assign to variable - if you assign to the same variable img then you replace original image.

img = img.convert(...)

That's all.

Related