我有一个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应用程序中,我使用配置为arraybuffer
的Axios将多个图像发送到/image/ocr
端点,并使用btoa
、String.fromCharCode
和Unit8Array
将返回的图像转换为Base64
:
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
}
}
问题是我发送了多个图像,例如this image和this image,端点/image/ocr
正在接受、处理和返回这些图像,但当我使用最后一个代码片段中的方法转换response.data
时,我只得到一个Base64
图像.
我看了看原始的response
,看看我是否可以迭代通过response.data
的ArrayBuffer
:
但它不适用于for(const image of response.data) {}
.我看到ArrayBuffer
有一个slice
方法,但我不确定这是否意味着两个图像都在ArrayBuffer
中,我需要切片然后转换,这很奇怪,因为到目前为止,至少有一个图像正在被转换为Base64
,或者因为我看到它可以用一些不同的方式完成,所以它被转换为另一种类型here,here和here.
如果
slice
选项是正确的,我不确定如何 Select 开始和结束,因为ArrayBuffer
中的值只是随机数字和符号.
你知道如何在我的Reaction应用程序上同时获得Base64
英寸的两张图像吗?