Hands-On Image Processing with Python
上QQ阅读APP看书,第一时间看更新

Converting from one file format to another

Using PIL, we can read an image in one file format and save it to another; for example, from PNG to JPG, as shown in the following:

im = Image.open("../images/parrot.png")
print(im.mode)

# RGB
im.save("../images/parrot.jpg")

But if the PNG file is in the RGBA mode, we need to convert it into the RGB mode before we save it as JPG, as otherwise it will give an error. The next code block shows how to first convert and then save:

im = Image.open("../images/hill.png")
print(im.mode)
# RGBA
im.convert('RGB').save("../images/hill.jpg") # first convert to RGB mode