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

落爺英雄遲暮 提交于 2019-12-05 15:39:22
coobird

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

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)][4] method
    • Used to specify an exact region from which to create a thumbnail.
  • [sourceRegion(Position, int, int)][5] 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.

[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)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!