Hi,
I suggest you to create a method (generate_binary_image) to do this and call it where you want in your code. The following code may help you, adjust it depending your needs.
from odoo import api, models, modules
from odoo.tools.mimetypes import guess_mimetype
import base64
import os
@api.one
def generate_binary_image(self, model, field, record_id):
"""
Allow to generate image from binary field into "files/model"
:param model: model
:param field: field name
:param record_id: ID of selected record
:return:
"""
record_id = self.env[model].sudo().browse(record_id)
# retrieving image binary data
binary_data = record_id.mapped(field)
# decoding image binary data
logo_decoded_data = base64.decodebytes(binary_data[0])
# get MIME type associated with the filename extension
mimetype = guess_mimetype(base64.b64decode(binary_data[0]))
if mimetype == 'image/png':
extension = '.png'
elif mimetype == 'image/jpeg':
extension = '.jpeg'
# get module path
module_path = modules.get_module_path('my_module')
if '\\' in module_path:
src_path = '\\static\\src\\files\\'
src_model_path = "{0}{1}\\".format('\\static\\src\\files\\', model)
else:
src_path = '/static/src/files/'
src_model_path = "{0}{1}/".format('/static/src/files/', model)
# if "model" folder does not exists create it
os.chdir("{0}{1}".format(module_path, src_path))
if not os.path.exists(model):
os.makedirs(model)
# create file if not exists in "model" folder else rewrite it
# the filename must be the record name value
name = record_id.name if record_id.name else '/'
file_path = "{0}{1}".format(module_path + src_model_path + str(name), extension)
if not os.path.exists(str(name)):
current_file = open(file_path, 'w+b')
else:
current_file = open(file_path, 'r+b')
current_file.write(logo_decoded_data)
current_file.close()
return "{0}{1}/{2}{3}".format('/my_module/static/src/files/', model, str(name), extension)
Best regards!