Reputation: 1331
Hope all stack members are alright .I am able to fetch binary data of Product image using code
p_ids=self.env.context.get('active_ids')
produtc_templates = self.env['product.template']
for p_id in p_ids:
binaryData = produtc_templates.search([('id', '=',p_id)]).image
data=base64.b64decode(binaryData)
file="marketplaces/rakuten_ftp/static/imageToSave_"+str(p_id)+".png"
with open(file, "wb") as imgFile:
imgFile.write(data)
Above code is create files from binary Data But i am failed to apply condition on mimetype base.Because when i query ir_attachment table with Products id's it return me False.
for p_id in p_ids:
attachments = self.env['ir.attachment']
mimetype=attachments.search([('res_id','=',p_id)])
I am considering res_id as Product id .But odoo failed to find any record against that id.So if any body have idea that how i can get mimetype against my product id then please help me.
Upvotes: 2
Views: 4916
Reputation: 1551
Your code looks good! But as per ir.attachement
object, binary data stored in datas
field. So, you can use that data to decode binary data to image file!!
Already tried below code into Odoo v11... & it's working as created new image file from binary data which is stored in datas
field!
product_image = self.env['ir.attachment']
product_images = product_image.search([('id', 'in', p_ids)])
for rec in product_images:
with open("imageToSave.jpg", "wb") as imgFile:
imgFile.write(base64.b64decode(rec.datas))
You can also add the condition for mimetype
as, p_ids
can contains multiple ids, so taking only those ids which have mimetype
of image/jpeg
or image/png
Below code snippet already checked with Odoo v11.0
import base64
from odoo.tools.mimetypes import guess_mimetype
p_ids = [16, 18, 11, 38, 39, 40] # Taking random ids of product.template
produtc_templates = self.env['product.template']
for p_id in p_ids:
binary_data = produtc_templates.search([('id', '=', p_id)]).image
mimetype = guess_mimetype(base64.b64decode(binary_data))
file_path = ""
if mimetype == 'image/png':
file_path = "/home/Downloads/" + str(p_id) + ".png"
elif mimetype == 'image/jpeg':
file_path = "/home/Downloads/" + str(p_id) + ".jpeg"
if file_path:
with open(file_path, "wb") as imgFile:
imgFile.write(base64.b64decode(binary_data))
Upvotes: 4
Reputation: 14768
Product images aren't saved as instances/records of ir.attachment
. OK, maybe that has changed, but i didn't find anything so fast.
What you can do, is using ir.attachment
's method _compute_mimetype()
Following example wasn't tested:
def get_mimetype_of_product_image(self, product_id)
product = self.env['product.product'].browse(product_id)
mimetype = self.env['ir.attachment']._compute_mimetype(
{'values': product.image})
return mimetype
Upvotes: 1