使用playwright解决requests无法下载的图片并解决PIL无法处理avif格式图片

# 在使用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

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cocktail_py

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值