Wednesday, May 22, 2013

Add text on image


With the AddTextToImage program you can add text to your image or photo and save the  update image in a new file or override the existing file. To add text to the image, first you need to open the image by selecting Open...from the File menu. When the image displays, select Add text to image from the Edit menu. Once the Add text to image window opens, you can type the text, select the font name and size, and choose the pen color. Then click OK to accept the settings. After that, click on the image where you want the text to show. If you want to stop displaying the text on the image where the mouse is clicked, pressed ESC key.

AddTextToImage 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;
Dimension ds;
int mX;
int mY;
int x;
int y;
static boolean imageLoaded;
boolean drawn;
boolean actionDraw;
MediaTracker mt;
Color colorTextDraw;
String imgFileName;
String fontName;
int fontSize;
String textToDraw;
public ImgArea(){

addMouseListener(new Mousexy()); //handle mouse event of the Canvas object
addKeyListener(new KList()); //handle the key event of the Canvas object
ds=getToolkit().getScreenSize(); //get the screen dimension--width and height
//x-axis and y-axis at the center of the screen
mX=(int)ds.getWidth()/2;
mY=(int)ds.getHeight()/2;

}

public void paint(Graphics g){
Graphics2D g2d=(Graphics2D)g;
if(imageLoaded){


if(drawn ){ //draw the update image on the screen
x=mX-bimg.getWidth()/2;
y=mY-bimg.getHeight()/2;
g2d.translate(x,y); //move the original coordinate to point (x,y)
g2d.drawImage(bimg,0,0,null); //draw the image at that point

}

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

}

class Mousexy extends MouseAdapter{

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


}

}catch(Exception ie){}


}


}

class KList extends KeyAdapter{
public void keyPressed(KeyEvent e){
if(e.getKeyCode()==27){ //ESC key is pressed, stop displaying the text
actionDraw=false;
textToDraw="";
fontName="";
fontSize=0;
}
}
}

//This method has code to add text to the update or original image
public void addTextToImage(int x,int y, BufferedImage img){
BufferedImage bi;
bi=(BufferedImage)createImage(img.getWidth(),img.getHeight()); //create blank  buffered image
Graphics2D  g2d=(Graphics2D)bi.createGraphics(); //create graphics object from blank  buffered image bi
g2d.setFont(new Font(fontName,Font.BOLD,fontSize)); //set font name, style, size of text
g2d.setPaint(colorTextDraw); //set text color
g2d.drawImage(img,0,0,null); //draw the image on the buffered image bi
g2d.drawString(textToDraw,x,y);//draw text on the buffered image bi
bimg=bi; //update the image
drawn=true; //there is any change to the image
g2d.dispose(); //clean the graphics object
repaint();
}

//intialize boolean variables
public void initialize(){
imageLoaded=false;
actionDraw=false;
drawn=false;
}

//cancel any change to image when the Cancel editing menu is selected
public void reset(String imgFileName){
if(imageLoaded){
prepareImage(imgFileName);
repaint();
}

}

//prepare the image before it is displayed
public void prepareImage(String filename){
initialize();
Image orImg;
try{
//use MediaTracker to wait for the image load
mt=new MediaTracker(this);
orImg=Toolkit.getDefaultToolkit().getImage(filename);
mt.addImage(orImg,0);
mt.waitForID(0);
//get width and height of image
int width=orImg.getWidth(null);
int height=orImg.getHeight(null);
//create buffered image object from the original image
orBufferedImage=createBufferedImageFromImage(orImg,width,height,false);
//create a blank buffered image bimg
bimg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
imageLoaded=true; //the image is loaded
}catch(Exception e){System.exit(-1);}
}


public void setActionDraw(boolean value ){
actionDraw=value;

}

//convert from image to buffered image
public BufferedImage createBufferedImageFromImage(Image image, int width, int height, boolean tran)
  {
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
public void saveToFile(String filename){
String ftype=filename.substring(filename.lastIndexOf('.')+1);
try{
if(drawn)
ImageIO.write(bimg,ftype,new File(filename));
else
ImageIO.write(orBufferedImage,ftype,new File(filename));
  }catch(IOException e){System.out.println("Error in saving the file");}
}

//set the text, font name, font size, and color
//this method is invoked when the btOK button in the TextAdd class
public void setText(String text,String fName, int fSize, Color color){
textToDraw=text;
fontName=fName;
fontSize=fSize;
if(color==null)
colorTextDraw=new Color(0,0,0);
else
colorTextDraw=color;
}
}

class  Main extends JFrame implements ActionListener{

ImgArea ia;
JFileChooser chooser;
JMenuBar mainmenu;
JMenu menufile;
JMenu menuedit;
JMenuItem mopen;
JMenuItem msaveas;
JMenuItem msave;
JMenuItem mexit;
JMenuItem maddtext;
JMenuItem mcancel;
String filename;
Main(){
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);

maddtext=new JMenuItem("Add text on image");
maddtext.setMnemonic(KeyEvent.VK_A);
maddtext.addActionListener(this);

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

menuedit.add(maddtext);
menuedit.add(mcancel);

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

setTitle("Add text to 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();
}
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 text on image")==0)
{
if(ImgArea.imageLoaded)
new TextAdd();
}

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

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

}
   

public class TextAdd extends JFrame implements ActionListener {
JPanel panel;
JTextArea txtText;
JComboBox cbFontNames;
JComboBox cbFontSizes;
JButton btOK;
JButton btSetColor;
String seFontName;
Color colorText;
int seFontSize;
TextAdd(){
colorText=null;
setTitle("Add text to the image");
setPreferredSize(new Dimension(400,150));

btOK=new JButton("OK");
btOK.setBackground(Color.BLACK);
btOK.setForeground(Color.BLUE);
btOK.addActionListener(this);

btSetColor=new JButton("Choose text color");
btSetColor.setBackground(Color.BLACK);
btSetColor.setForeground(Color.WHITE);
btSetColor.addActionListener(this);

txtText=new JTextArea(1,30);
cbFontNames=new JComboBox();
cbFontSizes=new JComboBox();
panel=new JPanel();
panel.setLayout(new GridLayout(4,1));
panel.add(new JLabel("Text:"));
panel.add(txtText);
panel.add(new JLabel("Font Name:"));
panel.add(cbFontNames);
panel.add(new JLabel("Font Size:"));
panel.add(cbFontSizes);
panel.add(btSetColor);
panel.add(btOK);
panel.setBackground(Color.GRAY);
add(panel, BorderLayout.CENTER);
setVisible(true);
pack();
listFonts();
}


public void actionPerformed(ActionEvent e){
if(e.getSource()==btOK){
ia.setActionDraw(true);
String textDraw=txtText.getText();
String fontName=cbFontNames.getSelectedItem().toString();
int fontSize=Integer.parseInt(cbFontSizes.getSelectedItem().toString());
ia.setText(textDraw,fontName,fontSize,colorText);
dispose();
}
else if(e.getSource()==btSetColor){
//display the color chooser dialog
JColorChooser jser=new JColorChooser();
colorText=jser.showDialog(this,"Color Chooser",Color.BLACK);

}
}

public void listFonts(){
//get the available font names and add them to the font names combobox
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
String[] fonts=ge.getAvailableFontFamilyNames();
for(String f:fonts)
cbFontNames.addItem(f);
//Initialize font sizes
for(int i=8;i<50;i++)
cbFontSizes.addItem(i);

}
}
//display File Open dialog for image file selection
public void setImage(){

int returnVal = chooser.showOpenDialog(this);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
filename=chooser.getSelectedFile().toString();
ia.prepareImage(filename);
enableSaving(true);
}
     
}
//open the File Save dialog
public void showSaveFileDialog(){
    int returnVal = chooser.showSaveDialog(this);
    if(returnVal == JFileChooser.APPROVE_OPTION) {
String filen=chooser.getSelectedFile().toString();
              ia.saveToFile(filen);
         
         }
}
public void enableSaving(boolean f){
msaveas.setEnabled(f);
msave.setEnabled(f);

}

}

public class AddTextToImage{

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


}

add text on image in Java

Adding text on the image is making change to the image data. In Java, the such image manipulation task can be performed after you convert the original image read from a file to a BufferedImage object. When you have the BufferedImage, you can add graphic elements to the object by using the methods of the Graphics2D class that is created from the BufferedImage object.  For more writing about Graphics2D, please read Graphics2D.

No comments:

Post a Comment