How can I resize an image using Java?

2019-01-01 03:06发布

I need to resize PNG, JPEG and GIF files. How can I do this using Java?

16条回答
唯独是你
2楼-- · 2019-01-01 03:20

You don't need a library to do this. You can do it with Java itself.

Chris Campbell has an excellent and detailed write-up on scaling images - see this article.

Chet Haase and Romain Guy also have a detailed and very informative write-up of image scaling in their book, Filthy Rich Clients.

查看更多
春风洒进眼中
3楼-- · 2019-01-01 03:22

If, having imagemagick installed on your maschine is an option, I recommend im4java. It is a very thin abstraction layer upon the command line interface, but does its job very well.

查看更多
听够珍惜
4楼-- · 2019-01-01 03:24

Java Advanced Imaging is now open source, and provides the operations you need.

查看更多
冷夜・残月
5楼-- · 2019-01-01 03:24

You could try to use GraphicsMagick Image Processing System with im4java as a comand-line interface for Java.

There are a lot of advantages of GraphicsMagick, but one for all:

  • GM is used to process billions of files at the world's largest photo sites (e.g. Flickr and Etsy).
查看更多
萌妹纸的霸气范
6楼-- · 2019-01-01 03:26

Simply use Burkhard's answer but add this line after creating the graphics:

    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

You could also set the value to BICUBIC, it will produce a better quality image but is a more expensive operation. There are other rendering hints you can set but I have found that interpolation produces the most notable effect. Keep in mind if you want to zoom in in a lot, java code most likely will be very slow. I find larger images start to produce lag around 300% zoom even with all rendering hints set to optimize for speed over quality.

查看更多
只若初见
7楼-- · 2019-01-01 03:28

It turns out that writing a performant scaler is not trivial. I did it once for an open source project: ImageScaler.

In principle 'java.awt.Image#getScaledInstance(int, int, int)' would do the job as well, but there is a nasty bug with this - refer to my link for details.

查看更多
登录 后发表回答