Recently, we have studied the cutting and splicing of images, using PIL. When we open the PNG format and save it as JPEG format, we find that an error is reported
1 import os
2 from PIL import Image
3
4
5 im = Image.open(r'E:\work\testcrop\test\hn1.png')
6 img_size = im.size
7 w = img_size[0]/2.0
8 h = img_size[1]
9 x = 0
10 y = 0
11 print("The image width and height are {}".format(img_size))
12 region = im.crop((x, y, x + w, y + h))
13 a = "1.jpeg"
14 region.save(a)
Error:
raise IOError(“cannot write mode %s as JPEG” % im.mode)
OSError: cannot write mode RGBA as JPEG
Looking up the data, it is found that PNG has four channels of RGBA, while JPEG has three channels of RGB. Therefore, when PNG is transferred to BMP, the program does not know what to do with channel a, and errors will occur
The solution is to check the number of channels and discard channel a
1 import os
2 from PIL import Image
3 path = r'E:\work\testcrop\test\hn2.png'
4 if 'png' in path[-4:]:
5 im = Image.open(path)
6 r, g, b, a = im.split()
7 im = Image.merge("RGB", (r, g, b))
8 os.remove(path)
9 im.save(path[:-4] + ".jpeg")
10 path = path[:-4] + ".jpeg"
11 im = Image.open(path)
12 img_size = im.size
13 w = img_size[0]/2.0
14 h = img_size[1]
15 x = 0
16 y = 0
17 print("The image width and height are {}".format(img_size))
18 region = im.crop((x, y, x + w, y + h))
19 a = "2.jpeg"
20 region.save(a)