Hello, I would like to know of any effective method that can help me compress the images that are uploaded to the site in a binary field and that they are saved compressed in my database.
Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:
Hello, I would like to know of any effective method that can help me compress the images that are uploaded to the site in a binary field and that they are saved compressed in my database.
Hi,
Python's 'PIL'(pillow) library can be used to compress images. You can use the following custom method:
from PIL import Image
from io import BytesIO
import base64
def compress_image(image_base64, quality=70):
# Decode the base64 image
image_data = base64.b64decode(image_base64)
# Open image with PIL
image = Image.open(BytesIO(image_data))
# Convert to RGB if needed
if image.mode in ("RGBA", "P"):
image = image.convert("RGB")
# Compress the image
output_io = BytesIO()
image.save(output_io, format="JPEG", quality=quality)
# Encode back to base64
compressed_image_base64 = base64.b64encode(output_io.getvalue()).decode('utf-8')
return compressed_image_base64
And modify your model’s write and create methods to automatically compress images on save>
from odoo import models, fields, api
class MyModel(models.Model):
_name = 'my.model'
image = fields.Binary("Image")
@api.model
def create(self, vals):
if vals.get('image'):
vals['image'] = compress_image(vals['image'])
return super(MyModel, self).create(vals)
def write(self, vals):
if vals.get('image'):
vals['image'] = compress_image(vals['image'])
return super(MyModel, self).write(vals)
Hope it helps
관련 게시물 | 답글 | 화면 | 활동 | |
---|---|---|---|---|
|
1
4월 23
|
4432 | ||
|
2
10월 21
|
3689 | ||
|
1
8월 21
|
3126 | ||
|
0
9월 18
|
2882 | ||
|
1
10월 21
|
6246 |