Using the Thumbnailator, can I make a sketch with the same height and width, regardless of image size

At Thumbnailator , I make thumbnails.

If the image size is 400 * 300, and if I do the following,

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

he creates a sketch of 160 * 120.

What I want, if I upload 400 * 300 images, it will center the scale so that I become 300 * 300, and then it will be thumbnails.

I looked through the documentation. Even I posted the same thing in a comment, but no luck.

+4
source share
1 answer

This seems to work for the [ sourceRegion ] [1] method, which can be used to specify the area from which the sketch should be created:

Illustration of creating a thumbnail using the <code> sourceRegion </code> method in Thumbnailator

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

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

Code above:

  1. Open original.jpg ,
  2. Use the center area of ​​the original image at 300 x 300 and
  3. Resize this area to a thumbnail of 160 x 160, and
  4. Writes in thumbnail.jpg .

You can select different areas of the original image by changing Positions.CENTER to, for example, Positions.TOP_LEFT . For a complete list of predefined options, see the Positions Listing documentation.


Below are some links to the Thumbnailator API documentation that may be of interest:

  • [ sourceRegion(int, int, int, int) ] [4] method
    • Used to indicate the exact region from which the sketch is created.
  • [ sourceRegion(Position, int, int) ] [5] method
    • Uses relative positioning using the Position object, as shown in the above code example.
  • sourceRegion(Rectangle) method
    • Used to indicate the exact region from which the thumbnail is created using the java.awt.Rectangle object.
  • Position enum
    • Provides predefined positions that can be used to indicate the relative position of the area from which the thumbnail is created.

Disclaimer: I support the Thumbnailator library.

[1]: https://web.archive.org/web/20160511015754/http://thumbnailator.googlecode.com:80/hg/javadoc/net/coobird/thumbnailator/Thumbnails.Builder.html#sourceRegion(net. coobird.thumbnailator.geometry.Position , int, int) [4]: https://web.archive.org/web/20160511015754/http://thumbnailator.googlecode.com:80/hg/javadoc/net/coobird/ thumbnailator / Thumbnails.Builder.html # sourceRegion (int , int, int, int) [5]: https://web.archive.org/web/20160511015754/http://thumbnailator.googlecode.com:80/hg/ javadoc / net / coobird / thumbnailator / Thumbnails.Builder.html # sourceRegion (net.coobird.thumbnailator.geometry.Position , int, int)

+10
source

Source: https://habr.com/ru/post/1399935/


All Articles