Search code examples
javaimageimage-resizing

Problems resizing an image


I´m trying to resize an image in Java but I have the next problem: enter image description here

This is the original image, but after the resizing code, the result it´s this: enter image description here

The code that I use it´s the next:

public BufferedImage res20x20(BufferedImage image){

    int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
    BufferedImage resizedIm= new BufferedImage(20, 20, type);
    Graphics2D g= resizedIm.createGraphics();
    g.drawImage(image, 0, 0, 20, 20, null);
    g.dispose();
    g.setComposite(AlphaComposite.Src);
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
    return resizedIm;
}

The entire code can be found here. The result that I want it´s this: enter image description here


Solution

  • try this

    public BufferedImage res20x20(BufferedImage image){
    
        int type = image.getType() == 0? BufferedImage.TYPE_INT_ARGB : image.getType();
        BufferedImage resizedIm= new BufferedImage(20, 20, type);
        Image scaledImage = inputImage.getScaledInstance(20, 20, Image.SCALE_SMOOTH);
        resizedIm.getGraphics().drawImage(scaledImage, 0, 0, null);
        return resizedIm;
    }
    

    Image.SCALE_SMOOTH is the type of algorithm use to scale the image, you can try different values to get the result that better work for your needs