如何从odoo中的二进制图像中获取完整路径

时间:2016-02-22 14:46:30

标签: python openerp python-imaging-library

我想使用PIL函数Image.open(),但它只有在我将图像路径作为参数传递时才有效。我必须找到一种方法来获得这个图像路径。我正在使用widget='image'odoo 8

1 个答案:

答案 0 :(得分:2)

图像存储在数据库中,base64编码。您必须自己将它们保存到文件中。

import tempfile
import base64
import os

from PIL import Image

from openerp import models, fields, api
from openerp.exceptions import UserError

class MyModel(models.Model):
    [...]
    image = fields.Binary()

    @api.multi
    def open_image(self):
        self.ensure_one()
        if not self.image:
            raise UserError("no image on this record")
        # decode the base64 encoded data
        data = base64.decodestring(self.image)
        # create a temporary file, and save the image
        fobj = tempfile.NamedTemporaryFile(delete=False)
        fname = fobj.name
        fobj.write(data)
        fobj.close()
        # open the image with PIL
        try:
            image = Image.open(fname)
            # do stuff here
        finally:
            # delete the file when done
            os.unlink(fname)