我可以在 Java 中更改 jpg 图像的分辨率吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11563307/
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-10-31 05:35:26  来源:igfitidea点击:

Can I change the resolution of a jpg image in Java?

javajpegimage-resizing

提问by Quintis555

I have some .jpg's that I'm displaying in a panel. Unfortunately they're all about 1500x1125 pixels, which is way too big for what I'm going for. Is there a programmatic way to change the resolution of these .jpg's?

我有一些 .jpg 显示在面板中。不幸的是,它们都是大约 1500x1125 像素,这对于我想要的来说太大了。有没有一种编程方式来改变这些 .jpg 的分辨率?

回答by toniedzwiedz

You can scale an image using Graphics2Dmethods (from java.awt). This tutorial at mkyong.comexplains it in depth.

您可以使用Graphics2D方法(来自java.awt)缩放图像。mkyong.com 上的教程对其进行了深入解释。

回答by Jonathan Payne

Load it as an ImageIcon and this'll do the trick:

将其作为 ImageIcon 加载,这样就可以解决问题:

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;

public static ImageIcon resizeImageIcon( ImageIcon imageIcon , Integer width , Integer height )
{
    BufferedImage bufferedImage = new BufferedImage( width , height , BufferedImage.TRANSLUCENT );

    Graphics2D graphics2D = bufferedImage.createGraphics();
    graphics2D.drawImage( imageIcon.getImage() , 0 , 0 , width , height , null );
    graphics2D.dispose();

    return new ImageIcon( bufferedImage , imageIcon.getDescription() );
}

回答by ewok

you can try:

你可以试试:

private BufferedImage getScaledImage(Image srcImg, int w, int h) {
    BufferedImage resizedImg = new BufferedImage(w, h, Transparency.TRANSLUCENT);
    Graphics2D g2 = resizedImg.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();
    return resizedImg;
}