How to combine two icons in java?

后端 未结 4 884
滥情空心
滥情空心 2020-12-19 18:54

I have two icons one is transparent so I need to add one icon and I have to add the transparent icon on top of that:

  public static void main(String[] args)         


        
4条回答
  •  太阳男子
    2020-12-19 19:32

    • Obtain a BufferedImage for each of the icons.
    • Create a BufferedImage (let us call it combinedImage) of the same size.
    • Call combinedImage.createGraphics() to get a Graphics2D (call it g) instance.
    • Paint the non-transparent image to g.
    • Paint the transparent image to g.
    • Dispose of g.
    • Use combinedImage for the icon.

    E.G.

    Merged Icons

    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    
    class MergedIcons {
    
        public static void main(String[] args) throws Exception {
            URL urlBG = new URL("http://i.stack.imgur.com/gJmeJ.png");
            URL urlFG = new URL("https://i.stack.imgur.com/5v2TX.png");
            final BufferedImage imgBG = ImageIO.read(urlBG);
            final BufferedImage imgFG = ImageIO.read(urlFG);
            // For simplicity we will presume the images are of identical size
            final BufferedImage combinedImage = new BufferedImage( 
                    imgBG.getWidth(), 
                    imgBG.getHeight(), 
                    BufferedImage.TYPE_INT_ARGB );
            Graphics2D g = combinedImage.createGraphics();
            g.drawImage(imgBG,0,0,null);
            g.drawImage(imgFG,0,0,null);
            g.dispose();
            Runnable r = () -> {
                JPanel gui = new JPanel(new GridLayout(1,0,5,5));
    
                gui.add(new JLabel(new ImageIcon(imgBG)));
                gui.add(new JLabel(new ImageIcon(imgFG)));
                gui.add(new JLabel(new ImageIcon(combinedImage)));
    
                JOptionPane.showMessageDialog(null, gui);
            };
            SwingUtilities.invokeLater(r);
        }
    }
    

提交回复
热议问题