Now there are 3 solutions to resize a image: 1st:
img = Image.open('C:\\Users\\Vishal\\Desktop\\Test\\xyx.jpg')
img = img.resize((90, 90), Image.ANTIALIAS)
img.save('C:\\Users\\Vishal\\Desktop\\Test\\xyz.jpg')
2nd :
img = Image.open('C:\\Users\\Vishal\\Desktop\\Test\\xyx.jpg')
bg = Image.new("RGB", img.size, (255, 255, 255))
bg.paste(img, img)
bg = bg.resize((90, 90), Image.ANTIALIAS)
bg.save('C:\\Users\\Vishal\\Desktop\\Test\\xyz.jpg')
and the 3rd:
img = Image.open('C:\\Users\\Vishal\\Desktop\\Test\\xyx.jpg')
img = img.convert('RGB')
img = img.resize((90, 90), Image.ANTIALIAS)
img.save('C:\\Users\\Vishal\\Desktop\\Test\\xyz.jpg')
For cases, The problems with 1st comes as error "cannot write mode RGBA as JPEG", for 2nd it comes as "bad transparency mask" and the problem with third is that it works in all cases but the images with transparency after resizing get their background as black which is not acceptable,also distorted colors pixels can be seen near the edges. So what can be the universal solution to these problems?
Note:(The output format required is .jpg and the images to be resized varies in the format as they are getting scraped, mostly .png with transparent background)
Update: As per comments I have placed an if else based on alpha condition as:
img = Image.open('C:\\Users\\Vishal\\Desktop\\Test\\xyx.jpg")
has_alpha = img.mode == 'RGBA'
print(has_alpha)
if has_alpha == True:
bg = Image.new("RGB", img.size, (255, 255, 255))
bg.paste(img, img)
bg = bg.resize((80, 80), Image.ANTIALIAS)
bg.save('C:\\Users\\Vishal\\Desktop\\Test\\xyz.jpg", quality=92)
else:
img.resize((80, 80), Image.ANTIALIAS)
img.save('C:\\Users\\Vishal\\Desktop\\Test\\xyz.jpg", quality=92)
It is working fine, But In some rare cases, has_alpha being false, I'm getting following error.
False
Traceback (most recent call last):
File "C:\Intel\lib\site-packages\PIL\JpegImagePlugin.py", line 620, in _save
rawmode = RAWMODE[im.mode]
KeyError: 'P'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "resize.py", line 33, in <module>
img.save('C:\\Users\\Vishal\\Desktop\\Test\\xyz.jpg", quality=92)
File "C:\Intel\lib\site-packages\PIL\Image.py", line 1935, in save
save_handler(self, fp, filename)
File "C:\Intel\lib\site-packages\PIL\JpegImagePlugin.py", line 622, in _save
raise IOError("cannot write mode %s as JPEG" % im.mode)
OSError: cannot write mode P as JPEG