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

131

我需要调整PNG、JPEG和GIF文件的大小。如何使用Java完成这个任务?


14
既然您要求一个库,真正的答案在这里:https://dev59.com/inVC5IYBdhLWcg3wlyQo#4528136。它比已接受的答案中的代码更容易使用 ;) - Artur Gajowy
我对库的部分持不同意见:Graphics2D是awt库的一部分,而且它是开源的。至于最后一部分(开源),我不是100%确定,但是谁会查看awt代码呢? - Burkhard
19个回答

1

提到了Image Magick。有一个JNI前端项目叫做JMagick。它不是特别稳定的项目(而且Image Magick本身已经知道经常改变并且甚至破坏兼容性)。尽管如此,我们在生产环境中使用JMagick和兼容版本的Image Magick执行高吞吐量、低延迟速度的缩放时取得了良好的经验。速度比我们之前尝试过的所有Java图形库都要快得多。

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


1

1

事实证明编写高性能的缩放器并不容易。我曾经为一个开源项目编写过一次:ImageScaler

原则上,“java.awt.Image#getScaledInstance(int,int,int)”也可以完成此工作,但有一个令人讨厌的错误-请参阅我的链接以获取详细信息。


0

如果您不想像@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;
        }
    }

0

首先设计 jLabel:

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

然后你可以编写下面的代码(添加自己的高度和宽度):

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

0

0

你也可以使用

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

0

我使用可自由获取的类(AnimatedGifEncoder、GifDecoder 和 LWZEncoder)开发了一个处理 GIF 动画的解决方案。
您可以下载 jgifcode jar 并运行 GifImageUtil 类。 链接:http://www.jgifcode.com


1
请在回答中提及您是否与您推荐的产品有关联。 - Hans Olsson
哇...这是用来调整GIF动画图像的吗?而且还是免费的??哇哇...我现在应该试一下... - gumuruh
是的,这是我开发的。这是它的源代码 https://github.com/rt29/jgifcode - 现在已经在这里了。我不再支持它。 - Rohit Tiwari

0
尝试以下方法:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接