我有一个任务,要求我从图像上传(jpg或png)中获取数据,根据需求调整其大小,然后将其转换为pdf,然后存储在s3中。
tobytes()?)
Pillow可用,所以我可以用它来调整图像的大小,现在文件类型是class 'PIL.Image.Image',我不知道如何继续。img2pdf库,但是当我有PIL格式时,我不知道如何使用它(使用PIL格式时,使用class 'PIL.Image.Image' s3上传看起来也像文件一样的对象,所以我不想在加载它之前将它保存到一个临时文件中。那么,在这种情况下我甚至需要img2pdf吗?我怎样才能达到这个目标?
编辑:我尝试使用tobytes()并直接上传到s3。上传很成功。但是,当下载以查看内容时,它会显示一个空页面。文件数据似乎没有写入pdf文件。
编辑2:实际上访问了s3并检查了存储的文件。当我下载并打开它时,它会显示cannot be opened
编辑3:我没有真正的工作代码,因为我还在试验什么可以工作,但下面是一个要点
data = request.FILES['file'].file # where the data is
im = Image.open(data)
(width, height) = (im.width // 2, im.height // 2) # example action I wanna take with Pillow
data = im_resized.tobytes()
# potential step for using img2pdf here but I don't know how
# img2pdf.convert(data) # this fails because "ImageOpenError: cannot read input image (not jpeg2000). PIL: error reading image: cannot identify image file <_io.BytesIO..."
# img2pdf.convert(im_resized) # this also fails because "TypeError: Neither implements read() nor is str or bytes"
upload_to_s3(data) # some function that utilizes boto3 to upload to s3发布于 2022-11-17 11:01:30
问题是你使用Image.Image对象而不是JPEG或类似的东西。
试试这个:
bytes_io = io.BytesIO()
image.save(bytes_io, 'PNG')
with open(output_pdf, "wb") as f:
f.write(img2pdf.convert(bytes_io.getvalue()))https://stackoverflow.com/questions/58458485
复制相似问题