java 在java中调整jpeg图像的大小

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

resize jpeg image in java

javaimage-processing

提问by janasainik

i am working on image comparison in java. I think before going to compare the images, it is better to process the images for setting a fixed size image. Is there any java functionality to resize the images. I want to rescale the images to 300*225.

我正在 Java 中进行图像比较。我认为在比较图像之前,最好先处理图像以设置固定大小的图像。是否有任何 Java 功能来调整图像大小。我想将图像重新缩放为 300*225。

回答by Bozho

BufferedImage img = ImageIO.read(imageFile);
Image scaled = img.getScaledInstance(300, 255, Image.SCALE_DEFAULT);

You can also take a look at the java-image-scalinglibrary.

您还可以查看java-image-scaling库。

回答by user489041


public ImageIcon resizeImage(String filePath, int w, int h) {


        String data = filePath;
        BufferedImage bsrc, bdest;
        ImageIcon theIcon;

//scale the image
        try
        {

            bsrc = ImageIO.read(new File(data));

            bdest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = bdest.createGraphics();
            AffineTransform at = AffineTransform.getScaleInstance((double) w / bsrc.getWidth(),
                    (double) h / bsrc.getHeight());
            g.drawRenderedImage(bsrc, at);

            //add the scaled image
            theIcon = new ImageIcon(bdest);
            return theIcon;
        }
        catch (Exception e)
        {
            System.out.println("This image can not be resized. Please check the path and type of file.");
            return null;
        }

     }


回答by Jigar Joshi

BufferedImage createResizedCopy(Image originalImage, 
                int scaledWidth, int scaledHeight, 
                boolean preserveAlpha)
{
    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;
}