我有一个小型Java程序,它在JLabels上使用ImageIcons来显示图片。我想带两个ImageIcons,将它们组合成一个ImageIcon,并将新的Image附加到JLabel,如下所示:
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;
我只是不确定如何去做,它只需要像我在油漆中打开两个图像文件,并在另一个的中间复制一个(pic2大约是pic1的一半大小)有什么提示吗?
答案 0 :(得分: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);
答案 1 :(得分: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);
}
答案 2 :(得分:1)
Compound Icon课程为您提供了以不同方式组合图标的灵活性。