2011-04-26 69 views
2

我有一個小型Java程序,它使用JLabels上的ImageIcons來顯示圖片。我想取兩個ImageIcons,將它們組合成一個單一的ImageIcon,並附加新的圖像與JLabel的,所以像:Java組合ImageIcons

ImageIcon img1 = new ImageIcon("src/inc/img/pic1.png"); 
ImageIcon img2 = new ImageIcon("src/inc/img/pic2.png"); 
//combine the two into a new Image 
// ? ImageIcon newImg = img1+img2; 

,我只是不知道如何去了解這一點,它只是需要就像我在paint中打開兩個圖像文件一樣,並將其中一個複製到另一個的中間(pic2大約是pic1大小的一半)任何提示?

回答

2

我沒有嘗試這樣做,但你應該能夠做這樣的事情(並排側吸引他們)

Image image1 = img1.getImage(); 
Image image2 = img2.getImage(); 
int w = image1.width + image2.width; 
int h = Math.max(image1.height, image2.height); 
Image image = new BufferedImage(w, h, TYPE_INT_RGB); 
Graphics2D g2 = image.createGraphics(); 
g2.drawImage(image1, 0, 0, null); 
g2.drawImage(image2, image1.width, 0, null); 
g2.dispose(); 

ImageIcon newImg = new ImageIcon(image); 
+0

一些小的變化,使第二個圖像居中在第一個,它的工作完全謝謝 – awestover89 2011-04-26 22:43:23

1

明白了正與此:

@Test 
    public void testIcon() throws IOException, InterruptedException { 
     File file1 = new File("/etc/alternatives/start-here-32.png"); 
     File file2 = new File("/etc/alternatives/start-here-24.png"); 

     BufferedImage img1 = ImageIO.read(file1); 
     BufferedImage img2 = ImageIO.read(file2); 

     img1.getGraphics().drawImage(img2, 0, 0, img2.getWidth(null), img2.getHeight(null), 0, 0, img2.getWidth(null), img2.getHeight(null), null); 
     showImage(img1); 
     Thread.sleep(10000); 
    } 

這裏是showImage方法:

 public void showImage(final BufferedImage image) { 
     JFrame frame = new JFrame(); 
     frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); 
     frame.setLayout(new BorderLayout()); 
     JPanel imagePanel = new JPanel() { 
      @Override 
      public void paint(java.awt.Graphics g) { 
       g.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), 0, 0, image.getWidth(), image.getHeight(), null); 

      }; 
     }; 

     frame.getContentPane().add(imagePanel, BorderLayout.CENTER); 
     frame.setSize(new Dimension(image.getWidth() + 100, image.getHeight() + 100)); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    }