如何使用 Java 调整图像大小?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/244164/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 11:58:11  来源:igfitidea点击:

How can I resize an image using Java?

javaimageresize

提问by pbreault

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

我需要调整 PNG、JPEG 和 GIF 文件的大小。我如何使用 Java 做到这一点?

采纳答案by Burkhard

After loading the image you can try:

加载图像后,您可以尝试:

BufferedImage createResizedCopy(Image originalImage, 
            int scaledWidth, int scaledHeight, 
            boolean preserveAlpha)
    {
        System.out.println("resizing...");
        int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
        BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
        Graphics2D g = scaledBI.createGraphics();
        if (preserveAlpha) {
            g.setComposite(AlphaComposite.Src);
        }
        g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null); 
        g.dispose();
        return scaledBI;
    }

回答by Ken Gentle

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

Java Advanced Imaging现在是开源的,并提供您需要的操作。

回答by Joel Carranza

If you are dealing with large images or want a nice looking result it's not a trivial task in java. Simply doing it via a rescale op via Graphics2D will not create a high quality thumbnail. You can do it using JAI, but it requires more work than you would imagine to get something that looks good and JAI has a nasty habit of blowing our your JVM with OutOfMemory errors.

如果您正在处理大图像或想要一个漂亮的结果,那么在 Java 中这不是一项微不足道的任务。简单地通过 Graphics2D 的重新缩放操作来完成它不会创建高质量的缩略图。您可以使用 JAI 来做到这一点,但它需要比您想象的更多的工作才能得到看起来不错的东西,而且 JAI 有一个坏习惯,就是用 OutOfMemory 错误来破坏我们的 JVM。

I suggest using ImageMagick as an external executable if you can get away with it. Its simple to use and it does the job right so that you don't have to.

如果可以的话,我建议使用 ImageMagick 作为外部可执行文件。它使用简单,可以正确完成工作,因此您不必这样做。

回答by David Koelle

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

你不需要图书馆来做到这一点。您可以使用 Java 本身来完成。

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

Chris Campbell 有一篇关于缩放图像的优秀而详细的文章- 请参阅这篇文章

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

Chet Haase 和 Romain Guy 在他们的书Filthy Rich Clients 中也有关于图像缩放的详细且信息量很大的文章。

回答by naltatis

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.

如果在您的机器上安装 imagemagick 是一种选择,我推荐im4java。它是命令行界面上的一个非常薄的抽象层,但它的工作非常好。

回答by Riyad Kalla

FWIW I just released (Apache 2, hosted on GitHub) a simple image-scaling library for Java called imgscalr(available on Maven central).

FWIW 我刚刚发布了(Apache 2,托管在 GitHub 上)一个简单的 Java 图像缩放库,称为imgscalr(在Maven central上可用)。

The library implements a few different approaches to image-scaling (including Chris Campbell's incremental approach with a few minor enhancements) and will either pick the most optimal approach for you if you ask it to, or give you the fastest or best looking (if you ask for that).

该库实现了几种不同的图像缩放方法(包括 Chris Campbell 的增量方法和一些小改进),并且如果您要求,它将为您选择最优化的方法,或者为您提供最快或最好的方法(如果您问那个)。

Usage is dead-simple, just a bunch of static methods. The simplest use-case is:

用法非常简单,只是一堆静态方法。最简单的用例是:

BufferedImage scaledImage = Scalr.resize(myImage, 200);

All operations maintain the image's original proportions, so in this case you are asking imgscalr to resize your image within a bounds of 200 pixels wide and 200 pixels tall and by default it will automatically select the best-looking and fastest approach for that since it wasn't specified.

所有操作都保持图像的原始比例,因此在这种情况下,您要求 imgscalr 在 200 像素宽和 200 像素高的范围内调整图像大小,默认情况下它会自动选择最佳外观和最快的方法,因为它不是'未指定。

I realize on the outset this looks like self-promotion (it is), but I spent my fair share of time googling this exact same subject and kept coming up with different results/approaches/thoughts/suggestions and decided to sit down and write a simple implementation that would address that 80-85% use-cases where you have an image and probably want a thumbnail for it -- either as fast as possible or as good-looking as possible (for those that have tried, you'll notice doing a Graphics.drawImage even with BICUBIC interpolation to a small enough image, it still looks like garbage).

我一开始就意识到这看起来像是自我推销(确实如此),但我花了相当多的时间在谷歌上搜索这个完全相同的主题,并不断提出不同的结果/方法/想法/建议,并决定坐下来写一篇一个简单的实现,可以解决 80-85% 的用例,其中您有一个图像并且可能想要一个缩略图——要么尽可能快,要么尽可能好看(对于那些尝试过的人,你会注意到即使使用 BICUBIC 插值对足够小的图像执行 Graphics.drawImage,它仍然看起来像垃圾)。

回答by coobird

Thumbnailatoris an open-source image resizing library for Java with a fluent interface, distributed under the MIT license.

Thumbnailator是一个用于 Java 的开源图像大小调整库,具有流畅的界面,在MIT 许可下分发

I wrote this library because making high-quality thumbnails in Java can be surprisingly difficult, and the resulting code could be pretty messy. With Thumbnailator, it's possible to express fairly complicated tasks using a simple fluent API.

我编写这个库是因为在 Java 中制作高质量的缩略图可能非常困难,而且生成的代码可能非常混乱。使用 Thumbnailator,可以使用简单流畅的 API 表达相当复杂的任务。

A simple example

一个简单的例子

For a simple example, taking a image and resizing it to 100 x 100 (preserving the aspect ratio of the original image), and saving it to an file can achieved in a single statement:

举个简单的例子,取一张图片,将其大小调整为 100 x 100(保留原始图片的纵横比),然后将其保存到文件中可以通过一条语句实现:

Thumbnails.of("path/to/image")
    .size(100, 100)
    .toFile("path/to/thumbnail");

An advanced example

高级示例

Performing complex resizing tasks is simplified with Thumbnailator's fluent interface.

使用 Thumbnailator 的流畅界面可以简化执行复杂的调整大小任务。

Let's suppose we want to do the following:

假设我们想要执行以下操作:

  1. take the images in a directory and,
  2. resize them to 100 x 100, with the aspect ratio of the original image,
  3. save them all to JPEGs with quality settings of 0.85,
  4. where the file names are taken from the original with thumbnail.appended to the beginning
  1. 将图像放在目录中,然后,
  2. 使用原始图像的纵横比将它们调整为 100 x 100,
  3. 将它们全部保存为质量设置为 的 JPEG 0.85
  4. 文件名取自原始文件thumbnail.并附加到开头

Translated to Thumbnailator, we'd be able to perform the above with the following:

转换为 Thumbnailator,我们将能够使用以下内容执行上述操作:

Thumbnails.of(new File("path/to/directory").listFiles())
    .size(100, 100)
    .outputFormat("JPEG")
    .outputQuality(0.85)
    .toFiles(Rename.PREFIX_DOT_THUMBNAIL);

A note about image quality and speed

关于图像质量和速度的说明

This library also uses the progressive bilinear scalingmethod highlighted in Filthy Rich Clientsby Chet Haase and Romain Guy in order to generate high-quality thumbnails while ensuring acceptable runtime performance.

该库还使用了Chet Haase 和 Romain Guy 在Filthy Rich Clients 中强调的渐进式双线性缩放方法,以生成高质量的缩略图,同时确保可接受的运行时性能。

回答by kajo

You could try to use GraphicsMagick Image Processing Systemwith im4javaas a comand-line interface for Java.

您可以尝试使用带有im4java 的GraphicsMagick 图像处理系统作为 Java 的命令行界面。

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

GraphicsMagick 有很多优点,但只有一个:

  • GM is used to process billions of files at the world's largest photo sites (e.g. Flickr and Etsy).
  • GM 用于处理世界上最大的图片网站(例如 Flickr 和 Etsy)上的数十亿个文件。

回答by Jice

Image Magick has been mentioned. There is a JNI front end project called JMagick. It's not a particularly stable project (and Image Magick itself has been known to change a lot and even break compatibility). That said, we've had good experience using JMagick and a compatible version of Image Magick in a production environment to perform scaling at a high throughput, low latency rate. Speed was substantially better then with an all Java graphics library that we previously tried.

已经提到了 Image Magick。有一个名为 JMagick 的 JNI 前端项目。它不是一个特别稳定的项目(众所周知,Image Magick 本身会改变很多甚至破坏兼容性)。也就是说,我们在生产环境中使用 JMagick 和兼容版本的 Image Magick 以高吞吐量、低延迟率执行扩展的经验很好。速度比我们之前尝试过的全 Java 图形库要好得多。

http://www.jmagick.org/index.html

http://www.jmagick.org/index.html

回答by Rohit Tiwari

I have developed a solution with the freely available classes ( AnimatedGifEncoder, GifDecoder, and LWZEncoder) available for handling GIF Animation.
You can download the jgifcode jar and run the GifImageUtil class. Link: http://www.jgifcode.com

我开发了一个解决方案,其中包含可用于处理 GIF 动画的免费类(AnimatedGifEncoder、GifDecoder 和 LWZEncoder)。
您可以下载 jgifcode jar 并运行 GifImageUtil 类。链接:http: //www.jgifcode.com