View Single Post
  #2 (permalink)  
Old 04-01-2008, 06:13 AM
hardwired hardwired is offline
Senior Member
 
Join Date: Jul 2007
Posts: 1,189
hardwired is on a distinguished road
Code:
import java.awt.*; import java.awt.event.*; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; import javax.swing.*; public class Collage extends JPanel { BufferedImage top; BufferedImage bottom; Point loc = new Point(); public Collage(BufferedImage[] images) { top = images[0]; bottom = images[1]; } protected void paintComponent(Graphics g) { super.paintComponent(g); int x = (getWidth() - bottom.getWidth())/2; int y = (getHeight() - bottom.getHeight())/2; g.drawImage(bottom, x, y, this); g.drawImage(top, loc.x, loc.y, this); } private void save() { int w = getWidth(); int h = getHeight(); int type = BufferedImage.TYPE_INT_RGB; BufferedImage save = new BufferedImage(w, h, type); Graphics2D g2 = save.createGraphics(); paint(g2); g2.dispose(); try { ImageIO.write(save, "jpg", new File("collage.jpg")); } catch(IOException e) { System.out.println("write error: " + e.getMessage()); } ImageIcon icon = new ImageIcon(save); JOptionPane.showMessageDialog(this, icon, "save", -1); } private JPanel getSouth() { JButton button = new JButton("save"); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { save(); } }); JPanel panel = new JPanel(); panel.add(button); return panel; } public static void main(String[] args) throws IOException { String[] ids = { "hawk", "blackBear" }; BufferedImage[] images = new BufferedImage[ids.length]; for(int j = 0; j < images.length; j++) { String path = "images/" + ids[j] + ".jpg"; images[j] = ImageIO.read(new File(path)); } Collage test = new Collage(images); test.addMouseListener(test.ml); JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(test); f.add(test.getSouth(), "Last"); f.setSize(400,400); f.setLocation(200,200); f.setVisible(true); } private MouseListener ml = new MouseAdapter() { public void mousePressed(MouseEvent e) { loc = e.getPoint(); repaint(); } }; }
Reply With Quote