Thursday, May 23, 2013

Add image to image

With the AddImageToImage program, you are easy to add an image to an original image. When the original image displays on the program interface, you can choose an image to add to this image by selecting the Add Image to Image from the Edit menu. The image to add to the original image can be resized before it is placed on the original image. The update image can be saved in a separate file or override the original file.  Placing many images on the original image is possible. If you want to cancel the editing, just select the Cancel editing from the Edit menu.

AddImageToImage source code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.image.*;
import java.awt.color.*;
import javax.swing.filechooser.*;
import java.io.*;
import java.awt.*;
import java.awt.geom.*;
import javax.imageio.*;
import javax.imageio.stream.*;

class ImgArea extends Canvas{

BufferedImage orBufferedImage;
BufferedImage bimg;
BufferedImage biToAdd;
Dimension ds;
int mX;
int mY;
int x;
int y;
static boolean imageLoaded;
boolean drawn;
boolean actionDraw;
MediaTracker mt;
Toolkit tk;

public ImgArea(){
addMouseListener(new Mousexy()); //handling mouse event of the Canvas object
addMouseMotionListener(new MouseMotionList());//handling mouse motion event of the Canvas object
addKeyListener(new KList());//handling key event of the Canvas object
tk=getToolkit(); //get Toolkit object fromt the current container
ds=tk.getScreenSize(); //get the screeen size-widtha and height
mX=(int)ds.getWidth()/2;//x-axis at the center of the screen
mY=(int)ds.getHeight()/2;//y-axis at the center of the screen

}

public void paint(Graphics g){
Graphics2D g2d=(Graphics2D)g;//create graphic2d object
if(imageLoaded){ //the image is loaded


if(drawn ){ //draw update image
x=mX-bimg.getWidth()/2;
y=mY-bimg.getHeight()/2;
g2d.translate(x,y);
g2d.drawImage(bimg,0,0,null);

}

else{ //draw the original image
x=mX-orBufferedImage.getWidth()/2;
y=mY-orBufferedImage.getHeight()/2;
g2d.translate(x,y);
g2d.drawImage(orBufferedImage,0,0,null);
}
}
g2d.dispose(); //clean the graphics2d object

}

class Mousexy extends MouseAdapter{

public void mousePressed(MouseEvent e){
try{
if(actionDraw){
if(drawn) //add image to the update image
addImageToImage(e.getX()-x,e.getY()-y, bimg);
else //add image to the original image
addImageToImage(e.getX()-x,e.getY()-y, orBufferedImage);


}

}catch(Exception ie){}


}


}

public class MouseMotionList extends MouseMotionAdapter{
public void mouseMoved(MouseEvent e){
if(actionDraw){
//create custom cursor from the image to be added to old image
Cursor cur=tk.createCustomCursor(biToAdd,new Point(1,1),"Image to add");
setCursor(cur);
}
}
}
class KList extends KeyAdapter{
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==27){ //the cancel key is pressed
actionDraw=false; //reset the drawing action
setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); //reset to the default cursor
}
}
}

public void addImageToImage(int x,int y, BufferedImage img){
BufferedImage bi;
bi=(BufferedImage)createImage(img.getWidth(),img.getHeight()); //create a blank bufferedimage
Graphics2D  g2d=(Graphics2D)bi.createGraphics(); //create graphics2d object from the blank bufferedimage
g2d.drawImage(img,0,0,null); //draw the old image on the blank bufferedimage
g2d.drawImage(biToAdd,x,y,null); //draw the new added image
bimg=bi; //update the image
drawn=true; //the new added image is drawn on the old image
g2d.dispose(); //clean the graphics2d object
repaint(); //repaint the drawing area so the update image can be shown
}

public void initialize(){ //initialize variables and set the default cursor type
imageLoaded=false;
actionDraw=false;
drawn=false;
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}

public void reset(String imgFileName){ //reset the drawing area when the Cancel editing menu is selected
if(imageLoaded){
prepareImage(imgFileName);
repaint();
}

}


public void prepareImage(String filename){
initialize();
Image orImg;
try{
mt=new MediaTracker(this); //create MediaTracker object
orImg=Toolkit.getDefaultToolkit().getImage(filename); //get the image from the chosen file
mt.addImage(orImg,0); //add the image to the tracker
mt.waitForID(0); //wait for image loading complete
int width=orImg.getWidth(null); //get the image width
int height=orImg.getHeight(null);//get the image height
orBufferedImage=createBufferedImageFromImage(orImg,width,height); //create bufferedimage from the original image
bimg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB); //create a blank bufferedimage
//the update image data will be stored in this bufferedimage
imageLoaded=true;//the image is loaded
}catch(Exception e){System.exit(-1);}
}


public void setActionDraw(boolean value ){//set the drawing action
actionDraw=value;

}

//create bufferedimage from an image
public BufferedImage createBufferedImageFromImage(Image image, int width, int height)
  {
BufferedImage dest ;
dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = dest.createGraphics();
    g2.drawImage(image, 0, 0, null);
    g2.dispose();
    return dest;
  }

//save the image to a file
public void saveToFile(String filename){
String ftype=filename.substring(filename.lastIndexOf('.')+1);
try{
if(drawn) //save the update image
ImageIO.write(bimg,ftype,new File(filename));
else //save the original image
ImageIO.write(orBufferedImage,ftype,new File(filename));
  }catch(IOException e){System.out.println("Error in saving the file");}
}
//set the new added image to the biToAdd bufferedimage variable
//this method is invoked when the use choose the image to add to the old image
public void setImageToAdd(BufferedImage biToAdd){
this.biToAdd=biToAdd;

}
}

//The MainInter class represents the main interface of the AddImateToImage program
//The center area of the interface is to show the image
//The interface has a menu bar that contains two menus: File and Edit
//With the File menu, you can select the image to show, save the image, and exit the program
//With Edit menu you can add image to the original image and cancel the editing
class  MainInter extends JFrame implements ActionListener{

ImgArea ia;
JFileChooser chooser;
JMenuBar mainmenu;
JMenu menufile;
JMenu menuedit;
JMenuItem mopen;
JMenuItem msaveas;
JMenuItem msave;
JMenuItem mexit;
JMenuItem maddimage;
JMenuItem mcancel;
String filename;
MainInter(){
ia=new ImgArea();
Container cont=getContentPane();
cont.add(ia,BorderLayout.CENTER );
mainmenu=new JMenuBar();
menufile=new JMenu("File");
menufile.setMnemonic(KeyEvent.VK_F);
menufile.addActionListener(this);

mopen=new JMenuItem("Open...");
mopen.setMnemonic(KeyEvent.VK_O);
mopen.addActionListener(this);

msaveas=new JMenuItem("Save as...");
msaveas.setMnemonic(KeyEvent.VK_S);
msaveas.addActionListener(this);

msave=new JMenuItem("Save");
msave.setMnemonic(KeyEvent.VK_V);
msave.addActionListener(this);

mexit=new JMenuItem("Exit");
mexit.setMnemonic(KeyEvent.VK_X);
mexit.addActionListener(this);
menufile.add(mopen);
menufile.add(msaveas);
menufile.add(msave);
menufile.add(mexit);

menuedit=new JMenu("Edit");
menuedit.setMnemonic(KeyEvent.VK_E);

maddimage=new JMenuItem("Add image to the image");
maddimage.setMnemonic(KeyEvent.VK_A);
maddimage.addActionListener(this);

mcancel=new JMenuItem("Cancel editing");
mcancel.setMnemonic(KeyEvent.VK_C);
mcancel.addActionListener(this);

menuedit.add(maddimage);
menuedit.add(mcancel);

mainmenu.add(menufile);
mainmenu.add(menuedit);
setJMenuBar(mainmenu);

setTitle("Add image to an image");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH);
    setVisible(true);

chooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "jpg", "gif","bmp","png");
    chooser.setFileFilter(filter);
    chooser.setMultiSelectionEnabled(false);
enableSaving(false);
ia.requestFocus();
}

//defines actions for menu item selections
public void actionPerformed(ActionEvent e){
JMenuItem source = (JMenuItem)(e.getSource());
if(source.getText().compareTo("Open...")==0)
{
setImage();
ia.repaint();
                                                     validate();

}
else if(source.getText().compareTo("Save as...")==0)
{
showSaveFileDialog();

}
else if(source.getText().compareTo("Save")==0)
{

ia.saveToFile(filename);
}
else if(source.getText().compareTo("Add image to the image")==0)
{
if(ImgArea.imageLoaded)
new ImageAdd();
}



else if(source.getText().compareTo("Cancel editing")==0) {
ia.reset(filename);
}

else if(source.getText().compareTo("Exit")==0)
System.exit(0);


}
   

public void setImage(){ //send the chosen image (by selecting the Open... menu) to ImgArea to show

int returnVal = chooser.showOpenDialog(this);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
filename=chooser.getSelectedFile().toString();
ia.prepareImage(filename);
enableSaving(true);
}
     
}

public void showSaveFileDialog(){ //display file save dialog
    int returnVal = chooser.showSaveDialog(this);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
String filen=chooser.getSelectedFile().toString();
              ia.saveToFile(filen);
         
         }
}



public void enableSaving(boolean f){//enable or disable saving sub-menu items
msaveas.setEnabled(f);
msave.setEnabled(f);

}

//This class represents an interface that allows you to select an image to add to the old image
public class ImageAdd extends JFrame implements ActionListener {
JLabel lblimage;
JPanel panel;
JButton btOK;
JTextField txtWidth;
JTextField txtHeight;
BufferedImage bi;
BufferedImage biReszied;
boolean resized=false;

ImageAdd(){
setTitle("Choose image");
setPreferredSize(new Dimension(600,250));
btOK=new JButton("OK");
btOK.setBackground(Color.BLACK);
btOK.setForeground(Color.BLUE);
btOK.addActionListener(this);

txtWidth=new JTextField(4);
txtWidth.addKeyListener(new KeyList());
txtHeight=new JTextField(4);
txtHeight.addKeyListener(new KeyList());
panel=new JPanel();
panel.setLayout(new FlowLayout());
panel.add(new JLabel("Width:"));
panel.add(txtWidth);
panel.add(new JLabel("Height:"));

panel.add(txtHeight);
panel.add(btOK);
panel.setBackground(Color.GRAY);
add(panel, BorderLayout.EAST);

lblimage=new JLabel();
add(lblimage, BorderLayout.CENTER);
setVisible(true);
pack();
addImage();
}

//this method defines code to open a file dialog for new image choosing
//the image data is read from the image file by using ImageIO.read method
//the image data is converted to byte array so it can used to construct an ImageIcon
//to show on the label lblimage
public void addImage(){
int returnVal = chooser.showOpenDialog(this);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
String filename=chooser.getSelectedFile().toString();
try{
bi=ImageIO.read(new File(filename));
ImageIcon img=new ImageIcon(imageToByte(bi));
lblimage.setIcon(img);
showImageDimension(bi);
repaint();
toFront();
}catch(IOException ie){}


}
     

}

//convert from bufferedimage to byte array
public byte[] imageToByte(BufferedImage bi){
ByteArrayOutputStream baos=new ByteArrayOutputStream();
try{
ImageIO.write(bi, "png", baos );
}catch(IOException ie){System.out.println("Image error");}
byte[] imageInByte=baos.toByteArray();

return imageInByte;
}

//this method defines code to resize the new image to add to the old image
//it is invoked when the user makes change to the txtWidth and txtHeight text boxes
//the user will sete resized image on the screen
public void resizeImage(BufferedImage bi,int w,int h){
biReszied=(BufferedImage)createImage(w,h);
Graphics2D g2d=(Graphics2D)biReszied.createGraphics();
g2d.drawImage(bi,0,0,w,h,null);
ImageIcon img=new ImageIcon(imageToByte(biReszied));
lblimage.setIcon(img);
repaint();
resized=true;
}

//Display the image width and height in the text boxes
public void showImageDimension(BufferedImage bi){
txtWidth.setText(""+bi.getWidth());
txtHeight.setText(""+bi.getHeight());
}

//when the user clicks the OK button the new image to add old image
//is sent to the ImgArea so it is ready to place on the old image
//once the user clicks on the old image
public void actionPerformed(ActionEvent e){
if(e.getSource()==btOK){
if(resized)
ia.setImageToAdd(biReszied);
else
ia.setImageToAdd(bi);
ia.setActionDraw(true);
dispose();
}
}

public class KeyList extends KeyAdapter{
  public void keyTyped(KeyEvent ke){

char c = ke.getKeyChar();
int intkey=(int)c;
if(!(intkey>=48 && intkey<=57 || intkey==8 || intkey==127)) //accept only number, backspace, and delete keys
{
ke.consume(); //hide the unwanted key

}
 
}
//when the user makes change to the txtWidth and txtHeight text boxes
//the image will be resized
  public void keyReleased(KeyEvent e){

if(!txtWidth.getText().equals("") && !txtHeight.getText().equals("")){
int width=Integer.parseInt(txtWidth.getText());
int height=Integer.parseInt(txtHeight.getText());
if(width>0 && height>0)
resizeImage(bi,width,height);
}

}
}

}


}

public class AddImageToImage{

public static void main(String args[]){
     new MainInter();
 
}


}

add image to image in Java

For code explanation, please read the comments along with the code of the program.

1 comment:

  1. I amazed with the research you made to make this actual submit incredible.
    Great activity!

    Have a look at my homepage;부산달리기


    ReplyDelete