Saving and resizing images in Odoo 8

Hi guys,

In this tutorial I will learn you how to create a new field that saves images, how to upload them correctly in your database and how to automatically resize them. With this demo you’ll learn how to instantly (automatically) resize uploaded images.

Tip:view my sample module here.

1. Create new fields

The first step is to create a new model and the new fields. For this demo I will create a clean, new table, but you could just simply add fields to an existing model.

As you can see I will create 4 fields. One to fill in a name and three fields of the type binary, which will be used to upload the images on. Every image field calls a field.function, which will then automatically resize the images:

So, what exactly does this do? The function get_image will find the correct image and returns it. Then the second function goes off, named _set_image. This function will call a pre-built function from Odoo to automatically resize the image.

2. Showing the new fields

Now that the model and fields are done they should also be showed. In my sample I will create a new menu item named ‘Images’ in the sales module, but you could just leave this out or place it anywhere else.

This will create a new menu item with the name ‘Images’, which is triggered by the action action_upload_images when the user clicks on it. The third record, view_images_form will show the fields and gives us the ability to visualise it as we want. Result:
Images view

3. Printing the images on a report

Now that the images can be saved and resized you should also be able to print them in your report!
Printing an image in a report is really easy:

This code will print the images out in the original format, in the 128x128px size and in 64x64px size. You simply need to call the image widget and you can print them out. When you’d print the report you would get something like this:
Printed image in multiple sizes

Tip: This whole tutorial is written in the Odoo V7 API. This is because Odoo 8 does not have fields.function and would complicate the task. If you’d really want it in Odoo 8 API you should have a look at computed fields.
Tip #2: You could also create an on_change event which then fills up different fields with different sizes of the images. This however would fill up the database much faster and is the reason why this is not in this tutorial.
Tutorial sponsored by Oocademy