# 在使用PIL处理avif格式图片的过程中会遇到以下问题
PIL.UnidentifiedImageError: cannot identify image file 'MFG_SG73Gseries.avif'
如果直接使用requests
无法下载图片,可能是由于图片链接需要特定的浏览器上下文或JavaScript渲染才能正确生成或访问。这时,可以利用Playwright
的浏览器自动化功能来访问页面,让JavaScript执行后再下载图片。以下是一个使用Playwright下载图片的示例代码:
# -*- coding: utf-8 -*-
# @Time : 2024/4/30 13:46
# @Author : Cocktail_py
import re
import base64
import asyncio
from PIL import Image
import pillow_avif
from playwright.async_api import async_playwright
url = "https://xxx/Photos/KOA-Speer-Electronics/MFG_SG73Gseries.jpg"
async def download_image_with_playwright(image_url, output_path):
async with async_playwright() as playwright:
browser = await playwright.chromium.launch(headless=False)
page = await browser.new_page()
await page.goto(image_url)
# 确保图片已加载,可以通过检查图片元素或等待一段时间来实现
await page.wait_for_load_state('networkidle')
# 获取图片的base64数据
image_base64 = await page.evaluate('''async () => {
const img = document.querySelector('img');
if (img && img.src) {
const response = await fetch(img.src);
if (response.ok) {
const blob = await response.blob();
return await new Promise(resolve => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
}
}
return null;
}''')
# 如果获取到了base64数据,则解码并保存为图片文件
print(image_base64)
if image_base64:
with open(output_path, "wb") as f:
imgstr = re.sub('data:image/.*?;base64,', '', image_base64)
bbb = base64.b64decode(imgstr)
f.write(bbb)
print(f"图片已保存至: {output_path}")
if 'image_base64' in 'avif':
img = Image.open(output_path)
img.save(output_path)
image = Image.open(output_path)
# 修复图片
image = image.convert("RGB")
# 保存修复后的图片
image.save(output_path, "JPEG")
else:
print("未找到图片或图片加载失败")
await browser.close()
await asyncio.sleep(1)
# 关闭浏览器
return 'success'
image_url = url
output_path = "666.jpg"
loop = asyncio.get_event_loop()
get_future = asyncio.ensure_future(download_image_with_playwright(image_url, output_path))
loop.run_until_complete(get_future) # 事件循环
print(get_future.result()) # 获取结果
#安装依赖
#pip install pillow-avif-plugin
from PIL import Image
import pillow_avif
img = Image.open('input.avif')
img.save('output.png')
参考:https://stackoverflow.com/questions/74527775/how-to-convert-avif-to-png-with-python