Custom JLabel Icon

I want to use java JLabel with a user size icon in my GUI. eg:

http://i.stack.imgur.com/XVglU.png

I used this code to resize the original icon:

    ImageIcon imageIcon = (ImageIcon) jLabel1.getIcon();// new ImageIcon( "Play-Hot-icon.png");

    ImageIcon thumbnailIcon = new ImageIcon(getScaledImage(imageIcon.getImage(), 25 , 25));
    jLabel1.setIcon(thumbnailIcon);

and here is the code for resizing the image

private Image getScaledImage(Image srcImg, int w, int h){

    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = resizedImg.createGraphics();

    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);

    g2.drawImage(srcImg, 0, 0, w, h, null);

    g2.dispose();
    return resizedImg;
}    

but after resizing the image and using this code, the result will be like this!

enter image description here

How can I get the desired image on my JLabel ??

Regards, sajad

+3
source share
1 answer

The problem is that when you create a scaled image, you use BufferedImage.TYPE_INT_RGBfor your new image, and the transparency becomes black with only TYPE_INT_RGB.

, BufferedImage.TYPE_INT_ARGB, -.

Image.getScaledInstance imageIcon , -, , , getScaledImage, .

+4

Source: https://habr.com/ru/post/1788894/


All Articles