程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Solution to the cannot write mode RGBA as JPEG problem in Python pilot module

編輯:Python

background

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


problem

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

programme

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)

Conclusion

  1. If the save format is jpg, It's better to add this conversion
  2. If the save format is 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')

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved