简体   繁体   English

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

[英]How can I resize an image using Java?

I need to resize PNG, JPEG and GIF files.我需要调整 PNG、JPEG 和 GIF 文件的大小。 How can I do this using Java?如何使用 Java 做到这一点?

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,它仍然看起来像垃圾)。

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;
    }

Thumbnailator is 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.我编写这个库是因为在 Java 中制作高质量的缩略图可能非常困难,而且生成的代码可能非常混乱。 With Thumbnailator, it's possible to express fairly complicated tasks using a simple fluent API.使用 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,使用原始图像的纵横比将它们调整为 100 x 100,
  3. save them all to JPEGs with quality settings of 0.85 ,将它们全部保存为质量设置为0.85 JPEG,
  4. where the file names are taken from the original with thumbnail.其中文件名取自带有thumbnail.的原始文件thumbnail. appended to the beginning附加到开头

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 scaling method highlighted in Filthy Rich Clients by Chet Haase and Romain Guy in order to generate high-quality thumbnails while ensuring acceptable runtime performance.该库还使用了 Chet Haase 和 Romain Guy 在Filthy Rich Clients 中强调的渐进式双线性缩放方法,以生成高质量的缩略图,同时确保可接受的运行时性能。

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 中也有关于图像缩放的详细且信息量很大的文章。

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

If you are dealing with large images or want a nice looking result it's not a trivial task in java.如果您正在处理大图像或想要一个漂亮的结果,那么在 Java 中这不是一项微不足道的任务。 Simply doing it via a rescale op via Graphics2D will not create a high quality thumbnail.简单地通过 Graphics2D 的重新缩放操作来完成它不会创建高质量的缩略图。 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.您可以使用 JAI 来做到这一点,但它需要比您想象的更多的工作才能得到看起来不错的东西,而且 JAI 有一个坏习惯,就是用 OutOfMemory 错误来破坏我们的 JVM。

I suggest using ImageMagick as an external executable if you can get away with it.如果可以的话,我建议使用 ImageMagick 作为外部可执行文件。 Its simple to use and it does the job right so that you don't have to.它使用简单,可以正确完成工作,因此您不必这样做。

If, having imagemagick installed on your maschine is an option, I recommend im4java .如果在您的机器上安装 imagemagick 是一种选择,我推荐im4java It is a very thin abstraction layer upon the command line interface, but does its job very well.它是命令行界面上的一个非常薄的抽象层,但它的工作非常好。

The Java API does not provide a standard scaling feature for images and downgrading image quality. Java API 不提供用于图像和降级图像质量的标准缩放功能。

Because of this I tried to use cvResize from JavaCV but it seems to cause problems.因此,我尝试使用 JavaCV 中的 cvResize 但它似乎会导致问题。

I found a good library for image scaling: simply add the dependency for "java-image-scaling" in your pom.xml.我找到了一个很好的图像缩放库:只需在 pom.xml 中添加对“java-image-scaling”的依赖。

<dependency>
    <groupId>com.mortennobel</groupId>
    <artifactId>java-image-scaling</artifactId>
    <version>0.8.6</version>
</dependency>

In the maven repository you will get the recent version for this.在 Maven 存储库中,您将获得最新版本。

Ex.前任。 In your java program在你的java程序中

ResampleOp resamOp = new ResampleOp(50, 40);
BufferedImage modifiedImage = resamOp.filter(originalBufferedImage, null);

You could try to use GraphicsMagick Image Processing System with im4java as 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 (eg Flickr and Etsy). GM 用于处理世界上最大的图片网站(例如 Flickr 和 Etsy)上的数十亿个文件。

Simply use Burkhard's answer but add this line after creating the graphics:只需使用 Burkhard 的答案,但在创建图形后添加这一行:

    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.您也可以将值设置为 BICUBIC,它会产生更好质量的图像,但操作成本更高。 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.请记住,如果您想放大很多,java 代码很可能会很慢。 I find larger images start to produce lag around 300% zoom even with all rendering hints set to optimize for speed over quality.我发现较大的图像开始产生大约 300% 缩放的滞后,即使所有渲染提示都设置为优化速度而不是质量。

It turns out that writing a performant scaler is not trivial.事实证明,编写一个高性能的缩放器并非易事。 I did it once for an open source project: ImageScaler .我为一个开源项目做过一次: 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.原则上 'java.awt.Image#getScaledInstance(int, int, int)' 也可以完成这项工作,但有一个令人讨厌的错误 - 请参阅我的链接了解详细信息。

Image Magick has been mentioned.已经提到了 Image Magick。 There is a JNI front end project called JMagick.有一个名为 JMagick 的 JNI 前端项目。 It's not a particularly stable project (and Image Magick itself has been known to change a lot and even break compatibility).它不是一个特别稳定的项目(众所周知,Image Magick 本身会改变很多甚至破坏兼容性)。 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.也就是说,我们在生产环境中使用 JMagick 和兼容版本的 Image Magick 以高吞吐量、低延迟率执行扩展的经验很好。 Speed was substantially better then with an all Java graphics library that we previously tried.速度比我们之前尝试过的全 Java 图形库要好得多。

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

You can use Marvin (pure Java image processing framework) for this kind of operation: http://marvinproject.sourceforge.net您可以使用 Marvin(纯 Java 图像处理框架)进行此类操作: http : //marvinproject.sourceforge.net

Scale plug-in: http://marvinproject.sourceforge.net/en/plugins/scale.html缩放插件: http : //marvinproject.sourceforge.net/en/plugins/scale.html

您可以使用以下流行产品: thumbnailator

If you dont want to import imgScalr like @Riyad Kalla answer above which i tested too works fine, you can do this taken from Peter Walser answer @Peter Walser on another issue though:如果您不想像上面的@Riyad Kalla 回答那样导入imgScalr ,我测试过也可以正常工作,您可以从Peter Walser 回答@Peter Walser 的另一个问题中执行此操作:

 /**
     * utility method to get an icon from the resources of this class
     * @param name the name of the icon
     * @return the icon, or null if the icon wasn't found.
     */
    public Icon getIcon(String name) {
        Icon icon = null;
        URL url = null;
        ImageIcon imgicon = null;
        BufferedImage scaledImage = null;
        try {
            url = getClass().getResource(name);

            icon = new ImageIcon(url);
            if (icon == null) {
                System.out.println("Couldn't find " + url);
            }

            BufferedImage bi = new BufferedImage(
                    icon.getIconWidth(),
                    icon.getIconHeight(),
                    BufferedImage.TYPE_INT_RGB);
            Graphics g = bi.createGraphics();
            // paint the Icon to the BufferedImage.
            icon.paintIcon(null, g, 0,0);
            g.dispose();

            bi = resizeImage(bi,30,30);
            scaledImage = bi;// or replace with this line Scalr.resize(bi, 30,30);
            imgicon = new ImageIcon(scaledImage);

        } catch (Exception e) {
            System.out.println("Couldn't find " + getClass().getName() + "/" + name);
            e.printStackTrace();
        }
        return imgicon;
    }

 public static BufferedImage resizeImage (BufferedImage image, int areaWidth, int areaHeight) {
        float scaleX = (float) areaWidth / image.getWidth();
        float scaleY = (float) areaHeight / image.getHeight();
        float scale = Math.min(scaleX, scaleY);
        int w = Math.round(image.getWidth() * scale);
        int h = Math.round(image.getHeight() * scale);

        int type = image.getTransparency() == Transparency.OPAQUE ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;

        boolean scaleDown = scale < 1;

        if (scaleDown) {
            // multi-pass bilinear div 2
            int currentW = image.getWidth();
            int currentH = image.getHeight();
            BufferedImage resized = image;
            while (currentW > w || currentH > h) {
                currentW = Math.max(w, currentW / 2);
                currentH = Math.max(h, currentH / 2);

                BufferedImage temp = new BufferedImage(currentW, currentH, type);
                Graphics2D g2 = temp.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g2.drawImage(resized, 0, 0, currentW, currentH, null);
                g2.dispose();
                resized = temp;
            }
            return resized;
        } else {
            Object hint = scale > 2 ? RenderingHints.VALUE_INTERPOLATION_BICUBIC : RenderingHints.VALUE_INTERPOLATION_BILINEAR;

            BufferedImage resized = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2 = resized.createGraphics();
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint);
            g2.drawImage(image, 0, 0, w, h, null);
            g2.dispose();
            return resized;
        }
    }

Try this folowing method :试试这个下面的方法:

ImageIcon icon = new ImageIcon("image.png");
Image img = icon.getImage();
Image newImg = img.getScaledInstance(350, 350, java.evt.Image.SCALE_SMOOTH);
icon = new ImageIcon(img);
JOptionPane.showMessageDialog(null, "image on The frame", "Display Image", JOptionPane.INFORMATION_MESSAGE, icon);

you can also use你也可以使用

Process p = Runtime.getRuntime().exec("convert " + origPath + " -resize 75% -quality 70 " + largePath + "");
            p.waitFor();

Design jLabel first:首先设计jLabel:

JLabel label1 = new JLabel("");
label1.setHorizontalAlignment(SwingConstants.CENTER);
label1.setBounds(628, 28, 169, 125);
frame1.getContentPane().add(label1);   //frame1 = "Jframe name"

Then you can code below code(add your own height and width):然后您可以编写以下代码(添加您自己的高度和宽度):

ImageIcon imageIcon1 = new ImageIcon(new ImageIcon("add location url").getImage().getScaledInstance(100, 100, Image.SCALE_DEFAULT)); //100, 100 add your own size
label1.setIcon(imageIcon1);

I have developed a solution with the freely available classes ( AnimatedGifEncoder, GifDecoder, and LWZEncoder) available for handling GIF Animation.我开发了一个解决方案,其中包含可用于处理 GIF 动画的免费类(AnimatedGifEncoder、GifDecoder 和 LWZEncoder)。
You can download the jgifcode jar and run the GifImageUtil class.您可以下载 jgifcode jar 并运行 GifImageUtil 类。 Link: http://www.jgifcode.com链接: http : //www.jgifcode.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM