希望所有堆栈成员都没事。我能够使用代码获取产品图像的二进制数据
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)
上面的代码是从二进制数据创建文件,但我无法在 mimetype 基础上应用条件。因为当我使用产品 id 查询 ir_attachment 表时,它返回 False。
for p_id in p_ids:
attachments = self.env['ir.attachment']
mimetype=attachments.search([('res_id','=',p_id)])
我正在考虑将 res_id 作为产品 id。但是 odoo 未能找到针对该 id 的任何记录。因此,如果有人知道如何根据我的产品 id 获取 mimetype,请帮助我。
最佳答案
你的代码看起来不错!但根据 ir.attachment 对象,二进制数据存储在 datas 字段中。因此,您可以使用该数据将二进制数据解码为图像文件!!
已经在Odoo v11中尝试了以下代码...并且它正在根据存储在datas
字段中的二进制数据创建新的图像文件!
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))
您还可以添加 mimetype
条件,因为 p_ids
可以包含多个 id,因此仅采用 mimetype
为 image/jpeg
或image/png
编辑#1
下面的代码片段已使用 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))
关于python - 将 odoo 图像存储到文件系统中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49747190/