Search code examples
javaimageimage-resizingjavax.imageiojai

Resize an image using Java


I have a JPEG Master Image which is of a dimension and an input Jpeg image of another dimension . So , I have written the following code to convert an image from one dimension to the other dimension. This code works fine when the input images are of dimensions around 900 * 700 and the master image of dimension 1200 * 800 . It does not work when the master/ input images are around dimensions like 3400*1900 and 4400*2400. Can anyone tell me where I went wrong!

public void checkSizeandResize(String file1, String file2){

   BufferedImage scaled = null;
   BufferedImage image1 = null;
   BufferedImage image2 = null;
   Graphics2D graphics2d = null;
   try{
    image1 = imageToBufferedImage(loadJPG(file1));
    image2 = imageToBufferedImage(loadJPG(file2));
    if(image1.getHeight()!=image2.getHeight() || image1.getWidth()!=image2.getWidth()){

            scaled = new BufferedImage(image2.getWidth(),image2.getHeight(), image2.getType());
            graphics2d =  scaled.createGraphics();
            graphics2d.setComposite(AlphaComposite.Src);
            graphics2d.drawImage(image1, 0, 0,null);
            graphics2d.dispose();
            ImageIO.write(image1, extension,new File(file2));

        }
    }
    catch(Exception exception)
    {
        exception.printStackTrace();
    }
    finally
    {
        scaled = null;
        image1 = null;
        image2 = null;
        graphics2d = null;
    }
}

Solution

  • So, I did a quick test (using ImageIO.read as you've not provided all the code) with an image going from 6144x4096 to 7680x4800 without a problem

    But I did notice that you are writing image1 instead of scaled

    ImageIO.write(image1, extension,new File(file2));
    

    Should probably be

    ImageIO.write(scaled, extension,new File(file2));
    

    You should also beware, that this isn't actually "scaling" the image so much as just changing the size of the resulting bitmap (image1 will remain at it's original size pixel size and painted within the scaled boundaries unmodified)

    If you're actually interested in changing the physical size of the image to match the corresponding boundaries, you might consider having a look at Java: maintaining aspect ratio of JPanel background image and Quality of Image after resize very low -- Java