[python]excel中url转图片

遇到的一个问题
图片url是webp格式,下载图片后,插入excel报错
报错信息

Traceback (most recent call last):
  File "excel_utils.py", line 86, in <module>
    obj.process_push_res("./uncheck_2021-10-12.xlsx", "./res1.xlsx")
  File "excel_utils.py", line 81, in process_push_res
    self.url2pic(target_file, target_file, sheet_name, col)
  File "excel_utils.py", line 66, in url2pic
    wb.save(target_file)
  File "/home/gzh/.local/lib/python3.7/site-packages/openpyxl/workbook/workbook.py", line 392, in save
    save_workbook(self, filename)
  File "/home/gzh/.local/lib/python3.7/site-packages/openpyxl/writer/excel.py", line 293, in save_workbook
    writer.save()
  File "/home/gzh/.local/lib/python3.7/site-packages/openpyxl/writer/excel.py", line 275, in save
    self.write_data()
  File "/home/gzh/.local/lib/python3.7/site-packages/openpyxl/writer/excel.py", line 94, in write_data
    self.manifest._write(archive, self.workbook)
  File "/home/gzh/.local/lib/python3.7/site-packages/openpyxl/packaging/manifest.py", line 181, in _write
    self._register_mimetypes(filenames=archive.namelist())
  File "/home/gzh/.local/lib/python3.7/site-packages/openpyxl/packaging/manifest.py", line 193, in _register_mimetypes
    mime = mimetypes.types_map[True][ext]
KeyError: '.webp'

原因:图片下载后,保存为后缀为.jpeg格式的文件,实际上该图片的格式还是.webp
解决方案:图片下载完成后,加一步格式转换,强制转换成jpeg

 # download_img
 res = requests.get(url)
 img = open(file_name, 'wb')
 img.write(res.content)
 img.close()
 ## 格式转换
 img = PIL.Image.open(file_name).convert("RGB")
 img.save(file_name, 'jpeg')

Image Conversion (JPG ⇄ PNG/JPG ⇄ WEBP) with Python

你可能感兴趣的:(python,python)