使用Java调整图像大小

41

我有一张PNG图片,我想将它调整大小。我该如何做呢?尽管我已经阅读了这篇文章,但我无法理解其中的代码片段。


1
你对那段代码片段到底不理解哪部分? - Heisenbug
1
你想生成原始PNG的调整大小版本,还是只是在UI中绘制调整大小的版本? - dcn
7个回答

91

如果你有一个java.awt.Image,调整其大小不需要任何额外的库。只需执行以下操作:

Image newImage = yourImage.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);

显然,将newWidthnewHeight替换为指定图像的尺寸。
注意最后一个参数:它告诉运行时您要使用的算法来调整大小。

有一些算法可以产生非常精确的结果,但这些算法需要很长时间才能完成。
您可以使用以下任何算法:

有关更多信息,请参见Javadoc


4
文档链接指向旧版本,请使用以下链接代替:http://download.oracle.com/javase/6/docs/api/java/awt/Image.html。 - Harry Joy

23

我们正在这样做来创建图像缩略图:

  BufferedImage tThumbImage = new BufferedImage( tThumbWidth, tThumbHeight, BufferedImage.TYPE_INT_RGB );
  Graphics2D tGraphics2D = tThumbImage.createGraphics(); //create a graphics object to paint to
  tGraphics2D.setBackground( Color.WHITE );
  tGraphics2D.setPaint( Color.WHITE );
  tGraphics2D.fillRect( 0, 0, tThumbWidth, tThumbHeight );
  tGraphics2D.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR );
  tGraphics2D.drawImage( tOriginalImage, 0, 0, tThumbWidth, tThumbHeight, null ); //draw the image scaled

  ImageIO.write( tThumbImage, "JPG", tThumbnailTarget ); //write the image to a file

10

试试这个:

ImageIcon icon = new ImageIcon(UrlToPngFile);
Image scaleImage = icon.getImage().getScaledInstance(28, 28,Image.SCALE_DEFAULT);

2
据我所知,由于其性能不佳(我记得很久以前在《富有的客户端》中读到过),不建议使用此方法(getScaledInstance())。 - jfpoilpret
1
不需要使用“ImageIcon”,可以直接使用“ImageIO.read(...)”。 - Alba Mendez
1
@AndrewThompson,您的链接似乎已经过时了。新位置是:https://community.oracle.com/docs/DOC-983611。 - Brian Matthews
1
感谢@BrianMatthews。不幸的是,我无法编辑原始评论,因此我将在此处进行更新:有关更多信息,请参见Image.getScaledInstance()的危险 - Andrew Thompson

4

高质量调整图片大小:

private static InputStream resizeImage(InputStream uploadedInputStream, String fileName, int width, int height) {

        try {
            BufferedImage image = ImageIO.read(uploadedInputStream);
            Image originalImage= image.getScaledInstance(width, height, Image.SCALE_DEFAULT);

            int type = ((image.getType() == 0) ? BufferedImage.TYPE_INT_ARGB : image.getType());
            BufferedImage resizedImage = new BufferedImage(width, height, type);

            Graphics2D g2d = resizedImage.createGraphics();
            g2d.drawImage(originalImage, 0, 0, width, height, null);
            g2d.dispose();
            g2d.setComposite(AlphaComposite.Src);
            g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
            g2d.setRenderingHint(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            ImageIO.write(resizedImage, fileName.split("\\.")[1], byteArrayOutputStream);
            return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        } catch (IOException e) {
            // Something is going wrong while resizing image
            return uploadedInputStream;
        }
    }

3
为什么您在drawImage()和dispose()之后设置渲染提示? - ykaganovich

1
            int newHeight = 150;
            int newWidth = 150; 
            holder.iv_arrow.requestLayout();
            holder.iv_arrow.getLayoutParams().height = newHeight;
            holder.iv_arrow.getLayoutParams().width = newWidth;
            holder.iv_arrow.setScaleType(ImageView.ScaleType.FIT_XY);
            holder.iv_arrow.setImageResource(R.drawable.video_menu);

1

在Java中的简单方法

public void resize(String inputImagePath,
            String outputImagePath, int scaledWidth, int scaledHeight)
            throws IOException {
        // reads input image
        File inputFile = new File(inputImagePath);
        BufferedImage inputImage = ImageIO.read(inputFile);
 
        // creates output image
        BufferedImage outputImage = new BufferedImage(scaledWidth,
                scaledHeight, inputImage.getType());
 
        // scales the input image to the output image
        Graphics2D g2d = outputImage.createGraphics();
        g2d.drawImage(inputImage, 0, 0, scaledWidth, scaledHeight, null);
        g2d.dispose();
 
        // extracts extension of output file
        String formatName = outputImagePath.substring(outputImagePath
                .lastIndexOf(".") + 1);
 
        // writes to output file
        ImageIO.write(outputImage, formatName, new File(outputImagePath));
    }

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

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