How to set image component size in Vaadin and keep aspect ratio

I have an image component that I would like to define as 500 pixels by 500 pixels. The problem is that my image is not square, but I would like to keep the aspect ratio when clicking StreamResource on the Image component. How to do this besides manually resizing the image? In other words, is there something in the Image component that allows me to automatically resize the image without causing it to become a square?

+7
java vaadin vaadin8
source share
3 answers

As a result, I decided to resize the image before sending it to the user interface. In other words, I do some calculations where, if the image is larger than 500, I then look if it is height or width, and then use what is the largest as the baseline. Then I multiply the aspect ratio to a different size and convert the image accordingly.

So, for example, if I have an image that is 800x600, I then assume that 800 is used as the baseline, which means that 500/800 means that the image should be reduced to 62.5% of its size. Then I reduce 600 by 62.5%, as in 600 * 0.625 = 375. Therefore, I resize the image using my image library to 500x375. And if the image was 600x800, I would resize it to 375x500. In other words, I pre-process the image and rely on something in the GUI to manage this for me.

+2
source share

With css, you can provide maximum width and height to achieve what you want.

First edit the mytheme.scss file and add the css entry. It should look something like this.

 @mixin mytheme { @include valo; .maxSize500 { max-width: 500px; max-height: 500px; } } 

To apply this rule using code, use addStyleName and set the size to undefined. Example:

 myImageComponent.setSizeUndefined(); // this line may not be needed in your project (it wasn't in mine) myImageComponent.addStyleName("maxSize500"); 

Now create, run the project, and you should be g2g.

HTHS!

+1
source share

I ran into this problem. I had to build my own logic to resize and width the image (s) based on the width of the browser pixel. I do not believe that there is anything out of the box in Vaadin that can handle it.

Something like that:

  if (browserWidth <= 1250){ height = x; width = x; }else if (browserWidth <= 1500){ height = x; width = x; }else if (browserWidth <= 1750){ height = x; width = x; }else if (browserWidth <= 2000){ height = x; width = x; }else { height = x; width = x; } 

Hope this helps.

-2
source share

All Articles