我有一个 FastAPI 端点/image/ocr
接受、处理并返回多个图像作为StreamingResponse
:
async def streamer(images):
for image in images:
# Bytes
image_bytes = await image.read()
# PIL PNG
image_data = Image.open(BytesIO(image_bytes))
# Process
# image_processed = ...
# Convert from PIL PNG to JPEG Bytes
image_ocr = BytesIO()
image_ocr.save(image_processed, format='JPEG')
yield image_ocr.getvalue()
@router.post('/ocr', summary='Process images')
async def ocr(images: List[UploadFile]):
return StreamingResponse(
streamer(images),
status_code=status.HTTP_200_OK,
media_type='image/jpeg'
)
在我的 React 应用程序中,我将多个图像发送到/image/ocr
使用 Axios 配置的端点arraybuffer
,并将返回的图像转换为Base64
using btoa
, String.fromCharCode
and Unit8Array
:
const imageSubmit = async data => {
const formData = new FormData()
// A `useRef` that stores the uploaded images
data?.current?.files?.successful.map(image =>
formData.append('images', image.data)
)
try {
const response = await request.post(
'/image/ocr',
formData,
{responseType: 'arraybuffer'}
)
const base64String = btoa(
String.fromCharCode(
...new Uint8Array(response.data)
)
)
const contentType = response.headers['content-type']
const fullBase64String = `data:${contentType};base64,${base64String}`
return fullBase64String
} catch (error) {
// Error log
}
}
问题是我要发送多张图像,例如,这个图片 https://i.stack.imgur.com/hRD1f.png and 这个图片 https://i.stack.imgur.com/n3ozM.png,正在被端点接受、处理并返回/image/ocr
,但是当我转换response.data
使用最后一个代码片段中的方法我只得到一个Base64
image.
我看了一眼原始的response
看看我是否可以迭代ArrayBuffer
我通过了response.data
:
数组缓冲区对象 https://i.stack.imgur.com/f0qBs.png
但它不起作用for(const image of response.data) {}
。我看到了ArrayBuffer
has a slice
方法,但我不确定这是否意味着这两个图像都在ArrayBuffer
我需要切片然后转换,这很奇怪,因为至少一张图像被转换为Base64
截至目前,或将其转换为另一种类型,因为我看到它可以通过一些不同的方式完成here https://stackoverflow.com/questions/71313129/how-to-render-streamable-image-on-react-coming-from-fastapi-server, here https://nono.ma/fetch-multiple-images-or-files-at-once-with-promises-in-typescript and here https://javascript.info/blob.
If the slice
选项是正确的,我不确定如何选择开始和结束,因为ArrayBuffer
只是随机数和符号。
关于如何获取这两个图像的任何想法Base64
在我的 React 应用程序上?