如何将PIL图像数组转换为Base64格式的PDF字符串?

2024-04-23 19:12:02 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的函数接受一个JSON字符串,其中包含一组base64编码的图像。我需要这个东西来返回一个base64编码的PDF,它是这样做的,但它只会给我一个页面,JSON字符串中的第一个图像。。。我有这个密码:

import json
import base64
from PIL import Image
from io import BytesIO
import numpy as np
import cv2

class ImageStuff(models.TransientModel):
   _name = 'image.camera_scan'
   _description = 'Do stuff with your images'

    @api.model
    def generate_pdf_from_b64(self, b64_arr_str):
       b64_arr = json.loads(b64_arr_str)
       pil_arr, count, pil0 = [], 0, False
       for blob in b64_arr:
           b64 = blob['b64'].split(',')[1]
           pil = Image.open(BytesIO(base64.b64decode(b64)))
           if count > 0: pil_arr.append(pil)
           else: pil0 = pil
           count += 1

       in_mem_file = BytesIO()

       pil0.save(in_mem_file, format="PDF", resolution=100.0, 
                 save_all=True, append_images=pil_arr) 
                 # I think it's that line above that doesn't work

       in_mem_file.seek(0)
       img_bytes = in_mem_file.read()
       base64_encoded_result_bytes = base64.b64encode(img_bytes)
       b64_str = base64_encoded_result_bytes.decode('ascii')

       return b64_str

我对python有点陌生(我相信你可以从代码中看到这一点)。但我希望尽可能避免使用python2.7中没有的模块。你知道吗

我用的是odoo10.0api,我不能用pip,所以导入新模块有点麻烦。尽管如此,如果你认为我真的没有办法只用PIL来完成,我还是非常欢迎你的帮助。你知道吗


Tags: infromimportjsonbytespilcountmem