You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何将StreamReader写入图片文件?含报错解决与追加需求

解决aiohttp获取图片写入文件的错误及追加文件方法

一、修复写入文件的TypeError问题

你遇到的TypeError: a bytes-like object is required, not 'StreamReader'是因为r.content是aiohttp的异步流对象(StreamReader),并非直接的字节数据,不能直接传给write()方法,bytes(r.content)也无法完成转换,必须通过异步读取操作获取字节内容。

修正后的代码示例

方式1:读取完整内容后写入(适合小文件)

import asyncio
import aiohttp

headerschrome = {...}  # 你的请求头配置
url = "..."  # 目标图片URL

async def fetch(s, url):
    async with s.request(method='GET', url=url) as r:
        r.raise_for_status()  # 自动捕获非200状态码并抛出异常
        content = await r.read()  # 异步读取完整字节内容
        with open('zzz/a.webp', 'wb') as xd:
            xd.write(content)

async def main():
    async with aiohttp.ClientSession(headers=headerschrome) as session:
        await fetch(session, url)

asyncio.run(main())

方式2:分块异步读取写入(适合大文件,避免占用过多内存)

async def fetch(s, url):
    async with s.request(method='GET', url=url) as r:
        r.raise_for_status()
        with open('zzz/a.webp', 'wb') as xd:
            # 每次读取1024字节的块,直到流读取完毕
            while chunk := await r.content.read(1024):
                xd.write(chunk)

二、将图片内容追加到单个文件

1. 单纯字节追加(生成字节拼接文件,不可直接作为图片打开)

如果仅需要把多个图片的字节数据拼接到同一个文件中,打开文件时使用ab(追加二进制)模式即可:

async def fetch_and_append(s, url, output_file='combined_data.bin'):
    async with s.request(method='GET', url=url) as r:
        r.raise_for_status()
        content = await r.read()
        with open(output_file, 'ab') as xd:
            xd.write(content)
            # 可选:添加自定义分隔符,方便后续拆分不同图片的字节内容
            xd.write(b'\n---IMAGE_SPLITTER---\n')

2. 合并为可查看的单张图片(需Pillow库支持)

如果要生成一张可直接查看的合并图片(比如纵向/横向拼接),需要用Pillow库做图像处理:

from PIL import Image
import io

async def fetch_and_merge(s, url, output_image='merged.webp'):
    async with s.request(method='GET', url=url) as r:
        r.raise_for_status()
        content = await r.read()
        # 将字节数据转为PIL Image对象
        current_img = Image.open(io.BytesIO(content)).convert('RGB')
        
        try:
            # 读取已存在的合并图片
            existing_img = Image.open(output_image).convert('RGB')
            # 计算纵向拼接后的尺寸
            new_width = max(existing_img.width, current_img.width)
            new_height = existing_img.height + current_img.height
            # 创建新画布并粘贴图片
            merged_img = Image.new('RGB', (new_width, new_height))
            merged_img.paste(existing_img, (0, 0))
            merged_img.paste(current_img, (0, existing_img.height))
        except FileNotFoundError:
            # 首次写入直接使用当前图片
            merged_img = current_img
        
        # 保存合并后的图片
        merged_img.save(output_image, format='WEBP')

使用前需安装Pillow:pip install pillow

内容的提问来源于stack exchange,提问作者charsee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 09:20:20