3

I created a method to resize the image from project resource package which holds the images and icons I use. However, it doesn't seem to render it or resize it smoothly.

public Image getResourceImage(String filepath){
        Image img = new ImageIcon(getClass().getClassLoader().getResource(filepath)).getImage();
        return img;
        /* Example usage: 
            Image loginBg = new ImageMethod().getAssetImage("foldername/filename.extension");
        */
    }

Below are the original png images.

enter image description here enter image description here

And below are the resized version which I'm using for the login panel.

enter image description here

It looks pixelated. Is there any way to achieve something as clear and smooth like this considering the original icon dimensions is 512x512

enter image description here

The icons are all in PNG format.

I've limited knowledge with Images in Java so I'd appreciate any help or suggestion.

Thanks.

I've finally solved it. Created 3 versions of my method.

public Image getResourceImage(String filepath){
        Image img = new ImageIcon(getClass().getClassLoader().getResource(filepath)).getImage();
        return img;
        /* Example usage: 
            Image loginBg = new ImageMethod().getAssetImage("foldername/filename.extension");
        */
    }

    public ImageIcon getResourceImage(String filepath, JLabel label){
        Image rawImage = new ImageIcon(getClass().getClassLoader().getResource(filepath)).getImage();
        Image renderedImage = rawImage.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
        ImageIcon image = new ImageIcon(renderedImage);
        return image;

    }

    public Image getResourceImage(String filepath, JPanel panel){
        Image rawImage = new ImageIcon(getClass().getClassLoader().getResource(filepath)).getImage();
        Image renderedImage = rawImage.getScaledInstance(panel.getWidth(), panel.getHeight(), Image.SCALE_SMOOTH);
        return renderedImage;

    }

This will definitely help the others. Thanks for the advice Obicere.

heisenberg
  • 1,784
  • 4
  • 33
  • 62
  • 1
    Have you tried manually scaling it to use a better method? [Image#getScaledInstance(int width, int height, int hints)](https://docs.oracle.com/javase/7/docs/api/java/awt/Image.html#getScaledInstance%28int,%20int,%20int%29) – Obicere May 21 '16 at 00:34
  • @Obicere Thank you very much for the suggestion. It worked. I created 3 versions of my method and Image.SCALE_SMOOTH did the trick. Thanks. – heisenberg May 21 '16 at 01:05
  • 3
    Start by having a look at [this example](http://stackoverflow.com/questions/14115950/quality-of-image-after-resize-very-low-java/14116752#14116752) and [The Perils of Image#getScaledInstance](http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html) – MadProgrammer May 21 '16 at 01:21

0 Answers0