This question has been flagged
1 Reply
175 Views

Hello!, 


 I have a binary fields and i need to fill it with a Image previously edited with PIL library, so for that i override default_get() function, 



    mapa=fields.Binary('')


    @api.model

    def default_get(self, fields):


        resul = super(ModelMap, self).default_get(fields)


    ​filepath='/odoo/odoo-server/addons/my_module/static/src/img/'

    ​mapa = Image.open(filepath+'Map_odoo.png').convert('RGB')


​**here i process mapa object**

until here its all ok, ​but now i try first:


    ​mapa.save(filepath+'Mapa_odoo_temp.png')

        resul['mapa']=filepath+'Mapa_odoo_temp.png'

​but doesnt work, raise a "Permission denied" because i cannot create that file , not in the module path and in any other path either, and idk how solve this...


​fo that i try another way, ​

​map2=open(filepath+"Mapa_odoo_temp.png", "wb")

    ​map2.write(base64.decodebytes(mapa))

    ​map2.close()

        resul['mapa']=filepath+'Mapa_odoo_temp.png'


​​but doesnt work too


​so finally try giving the image directly  

        resul['mapa']=mapa

​ 

​but this dont crash but dont display the image "the image cannot be loaded" or something similar.


 Could somebody tell me how i could do? so thanks.

 

Avatar
Discard
Best Answer

Hi,


To fill a binary field with an image processed using the PIL library in Odoo, you need to convert the image to a base64 encoded string and then assign it to the binary field.


Here's how you can modify your default_get function:


from PIL import Image

import base64

from io import BytesIO

from odoo import api, fields, models



class ModelMap(models.Model):

    _name = 'model.map'

    mapa = fields.Binary('Map Image')

    @api.model

    def default_get(self, fields):

        resul = super(ModelMap, self).default_get(fields)

        filepath = '/odoo/odoo-server/addons/my_module/static/src/img/'

        with Image.open(filepath + 'Map_odoo.png').convert('RGB') as mapa:

            mapa = mapa.resize((100, 100))

            buffer = BytesIO()

            mapa.save(buffer, format='PNG')

            image_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8')

            resul['mapa'] = image_base64

        return result


Hope it helps

Avatar
Discard
Author

Yes! its perfect, so thanks. its solved.

Author

Sorry i need to ask again, because this work, but dont apply the changes when i do "mapa.save(buffer, format='PNG')"... you know what can be?

Author

add info: if i apply a "resize((64,64))" after all yes this make effect, but for some reason dont read good the ImageDraw chages (apply lines) and some changes pixel-by-pixel that i made in the image in array mode.
Important to say that all this proces work fine when i do out of odoo, in a python script directly