Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Thumbnailator, can i make thumbnail with same height and width regardless the image size

In Thumbnailator, i am making thumbnails.

If image size is 400*300 and if i do following thing,

Thumbnails.of(new File("original.jpg"))
        .size(160, 160)
        .toFile(new File("thumbnail.jpg"));

it create thumbnail of 160*120.

What i want is if i upload 400*300 image, it will center zoom so that i will become 300*300 and then it will thumbnail.

I gone through the documentation, Even i posted same thing over there in comment but no luck.

like image 286
KuKu Avatar asked Dec 21 '22 01:12

KuKu


1 Answers

Sounds like a job for the sourceRegion method which can be used to specify the region from which the thumbnail should be produced:

Illustration of creating a thumbnail using the sourceRegion method in Thumbnailator

In your particular case, you'll want to try the following:

Thumbnails.of(new File("original.jpg"))
  .sourceRegion(Positions.CENTER, 300, 300)
  .size(160, 160)
  .toFile(new File("thumbnail.jpg"));

The above code will:

  1. Open the original.jpg,
  2. Use the central 300 x 300 region of the original image, and
  3. Resize that region to a 160 x 160 thumbnail, and
  4. Writes to the thumbnail.jpg.

It's possible to select different regions of the original image by changing Positions.CENTER to, for example, Positions.TOP_LEFT. For a complete list of pre-defined choices, please look at the documentation for the Positions enum.


The following are some links to the Thumbnailator API documentation which may be of interest:

  • sourceRegion(int, int, int, int) method
    • Used to specify an exact region from which to create a thumbnail.
  • sourceRegion(Position, int, int) method
    • Uses relative positioning using the Position object as shown in the example code above.
  • sourceRegion(Rectangle) method
    • Used to specify an exact region from which to create a thumbnail, using a java.awt.Rectangle object.
  • Position enum
    • Provides pre-defined positions which can be used to specify the relative position of the region from which to create a thumbnail.

Disclaimer: I am the maintainer of the Thumbnailator library.

like image 73
coobird Avatar answered Apr 29 '23 09:04

coobird