1

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

F.Stan
  • 553
  • 1
  • 10
  • 23
  • 3
    A Graphics object cannot be used after it has been disposed. Even if it could, you are setting rendering hints after calling drawImage, so they would have no effect. Set your rendering hints before you call drawImage. – VGR Jun 23 '17 at 16:16
  • https://stackoverflow.com/questions/1069095/how-do-you-create-a-thumbnail-image-out-of-a-jpeg-in-java – digidude Jun 23 '17 at 16:17

1 Answers1

1

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

David Florez
  • 1,460
  • 2
  • 13
  • 26