Recently, I was solving a problem : How to automatically intercept Excel The range inside is pictures and send . Finally using pywin32
Module solves , But when sending , There will be some problems with some deployed computers , This is the following error report
cannot write mode RGBA as JPEG
Later, I found that some computers were using VBA Of CopyPicture
Method defaults to PNG Format , Some defaults are JPG Format , Bizarre
The problem is the following paragraph , For better understanding , I put the context out
img = ImageGrab.grabclipboard()
imgpath = os.path.join(os.path.dirname(__file__),'{imgname}.{fmt}'.format(imgname=time.strftime('%Y%m%d%H%M%S'),fmt=fmt))
img.save(imgpath) # There is a mistake in this sentence
The complete information of error reporting is as follows
Traceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\JpegImagePlugin.py", line 611, in _save
rawmode = RAWMODE[im.mode]
KeyError: 'RGBA'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:\onedrive\doc\for_share\Python_eco\python\work_wechat_amiba.py", line 22, in <module>
amiba()
File "D:\onedrive\doc\for_share\Python_eco\python\work_wechat_amiba.py", line 14, in amiba
img = excel.savePic(['post'],'jpg')
File "D:\onedrive\doc\for_share\Python_eco\python\Udfs\cls_excel.py", line 80, in savePic
img.save(self._picPath)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\Image.py", line 2151, in save
save_handler(self, fp, filename)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python39\lib\site-packages\PIL\JpegImagePlugin.py", line 613, in _save
raise OSError(f"cannot write mode {im.mode} as JPEG") from e
OSError: cannot write mode RGBA as JPEG
The solution is also very simple , Add a conversion
img = ImageGrab.grabclipboard()
imgpath = os.path.join(os.path.dirname(__file__),'{imgname}.{fmt}'.format(imgname=time.strftime('%Y%m%d%H%M%S'),fmt=fmt))
img.convert('RGB') # This sentence
img.save(imgpath)
jpg
, It's better to add this conversion png
, You don't have to say that If you have a format variable , The final addition is as follows
if fmt == 'jpg':
img.convert('RGB')