Вы находитесь на странице: 1из 1

Ще Наступний блог» Створити блог Вхід

Java programs
This site provides you the opportunity to learn Java programming language by programs.

Home Java Programs Random Posts Programming Tutorials Programming Exercises Programming Tips

MONDAY, JUNE 3, 2013


SEARCH THIS BLOG
Image Editor Custom Search
Search
The ImageEditor program is a simple program that can help you to write Java code to
edit image or photo file. This image editor program can do the following image editing
tasks: JAVA BLOG ARCHIVE
-adding text to the image, ► 2014 (2)
-changing the brightness of the image, ▼ 2013 (160)
-compressing the image,
► December (2)
-resizing the image
-rotating the image, and ► November (8)
-making the background of the image transparent (single background color), and ► October (14)
-save the edited image on your local disk drive. ► September (9)

► August (29)
► July (34)
▼ June (18)
Word to Text Converter
Text To Word Converter
Extract images from PDF
PDF To JPG Converter
JPG To PDF Converter
PDF To Text Converter
Text to PDF Converter
Phonebook

Merge pdf files


Split Pdf
Create a pdf
Contact List
Edit picture color

ImageEditor source code: Photo Viewer


Print To Printer
import java.awt.*;
Screen recording
import java.awt.event.*;
import javax.swing.*; Image Editor
import javax.swing.event.*; JPEG Converter
import java.awt.image.*;
import java.awt.color.*; ► May (17)
import javax.swing.filechooser.*; ► April (28)
import java.io.*;
► March (1)
import java.awt.*;
import java.awt.geom.*;
import javax.imageio.*; LABELS
import javax.imageio.stream.*;
random post (83) source
////start the ImgArea class code (69) Java (51)
//The ImgArea class acts as a drawing area of the Image Editor program program (50) Swing (24) Java
program (23) class (12) image (11) awt
class ImgArea extends Canvas{ (8) itemlistener (5) docx (3) itemevent (3) layout
manager (3) pdf (3) AbstractAction (2)
Image orImg; ButtonGroup (2) ChangeListener (2) LinkedList
BufferedImage orBufferedImage; (2) Set (2) TreeMap (2) ZipEntry (2)
actionlistener (2) adjustment event (2)
BufferedImage bimg;
background (2) calculator (2) converter (2) draw
BufferedImage bimg1;
(2) extract images (2) itext (2) keylistener (2)
float e; microsoft word (2) recorder (2) ArrayDeque (1)
float radian; ArrayList (1) Attribute (1) BufferedReader (1)
Dimension ds; BufferedWriter (1) Collections (1) Comparator (1)
int mX; DataInputStream (1) DataOutputStream (1)
int mY; DateFormat (1) DecialFormat (1) DefaultListModel (1)
int x; Deque (1) Desktop (1) DropTarget (1) FileInputStream

int y; (1) FileOutputStream (1) FileReader (1) FileWriter (1)


FilenameFilter (1) Graphics (1) Graphics2D (1)
static boolean imageLoaded;
GridBagLayout (1) HashMap (1) IP address (1)
boolean actionSlided;
ImageIcon (1) Iterator (1) JButton (1) JCheckBox (1)
boolean actionResized; JCheckBoxMenuItem (1) JColorChooser (1)
boolean actionCompressed; JComboBox (1) JConsole (1) JFileChooser (1)
boolean actionTransparent; JFormattedTextField (1) JFrame (1) JFreeChart (1)
boolean actionRotated; JLabel (1) JList (1) JMenu (1) JMenuBar (1)
boolean actionDraw; JPasswordField (1) JPopupMenu (1) JProgressBar (1)
boolean drawn; JRadioButton (1) JRadioButtonMenuItem (1)

MediaTracker mt; JScrollPane (1) JSlider (1) JSpinner (1) JTable (1)
JTextArea (1) JTextField (1) JTextPane (1) JToolBar (1)
static Color c;
JTree (1) ListCellRenderer (1) ListIterator (1) Locale (1)
Color colorTextDraw;
MouseEvent (1) MouseListener (1)
Robot rb; MouseMotionListener (1) NumberFormat (1)
boolean dirHor; ObjectInputStream (1) ObjectOutputStream (1) SQLite
String imgFileName; (1) Serializable (1) SimpleDateFormat (1) StringBuilder
String fontName; (1) Toolkit (1) ZipFile (1) ZipOutputStream (1)
int fontSize; actionevent (1) add image to image (1) add text to
String textToDraw; image (1) adjustmentlistener (1) amortization (1)

public ImgArea(){ analyzer (1) animation (1) applet (1) array (1) array
manipulation (1) arrays (1) audio (1) automation (1)
background process (1) bar chart (1) borderlayout (1)
addMouseListener(new Mousexy()); //hanlding mouse event of Canvas class
brightness (1) bufferedimage (1) bufferedimage to byte
addKeyListener(new KList()); //handling key event of the Canvas array (1) bufferedimage to image (1) button (1)
try{ calculation (1) capture (1) capture screen (1) celsius
rb=new Robot(); //create Robot object (1) change event (1) charts in Java (1) checkbox (1)
}catch(AWTException e){} checkboxgroup (1) checker (1) choice (1) clock (1)
color (1) combine (1) compression (1) contact list (1)
ds=getToolkit().getScreenSize(); //get the screen size conversion (1) convert string to date (1) convert string

mX=(int)ds.getWidth()/2; //half of the screen width to number (1) copy files (1) count words frequency (1)
counter (1) create and extract jar file (1) create image
mY=(int)ds.getHeight()/2;//half of the screen height
(1) create pdf (1) currency conversion (1) currency
exchange (1) cursor position (1) database (1) date add
} (1) date diff (1) date time (1) display (1) document
event (1) documentation in Java (1) documentlistener
public void paint(Graphics g){ (1) download (1) drag and drop (1) drawing (1) e-mail
Graphics2D g2d=(Graphics2D)g; //create Graphics2D object (1) edit picture color (1) event (1) extract links from
if(imageLoaded){ html (1) extract zip (1) fahrenheit (1) file (1) file view (1)
files (1) final (1) flowlayout (1) focuseven (1)

//draw the update image focuslistener (1) font (1) format date (1) format number
(1) fraction (1) frame (1) ftp client (1) ftp server (1)
if(actionSlided || actionResized || actionTransparent || actionRotated || drawn ){
generics (1) gridlayout (1) guess (1) hello world (1)
x=mX-bimg.getWidth()/2;
host name (1) html to pdf converter (1) image editor (1)
y=mY-bimg.getHeight()/2; image to bufferedimage (1) image viewer (1)
g2d.translate(x,y); //move to coordinate (x,y) imagefilter (1) imageproducer (1) interface (1) item
g2d.drawImage(bimg,0,0,null); //draw the iamge event (1) jar pack (1) java code (1) java mail (1) java
programs (1) javadoc (1) jdom (1) jpeg (1) jpg to pdf
} converter (1) keyevent (1) label (1) launch e-mail client
(1) learn java by programs (1) lines (1) list (1) login

else{ //draw the original image form (1) math calculator (1) max (1) measurement (1)
merge (1) merge pdf (1) mouse and key controls (1)
x=mX-orBufferedImage.getWidth()/2;
move files (1) number (1) open and print file (1) open
y=mY-orBufferedImage.getHeight()/2;
browser (1) password check (1) password checker (1)
g2d.translate(x,y); //move to coordinate (x,y) password protection (1) pdf reader (1) pdf to jpg
g2d.drawImage(orBufferedImage,0,0,null); //draw image converter (1) pdf to text converter (1) performance and
} resources consumption assessment (1) phonebook (1)
} photo viewer (1) power (1) print (1) printer (1) programs
g2d.dispose(); //clean the Graphic2D object (1) quiz (1) random (1) recording (1) resize (1) robot (1)
rotate (1) runnable (1) sale calculator (1) save chart in

} pdf and png image files (1) screen (1) screen recording
(1) screen size (1) scrollbar (1) send e-mail (1)
slideshow (1) sound (1) sound player (1) source doe
class Mousexy extends MouseAdapter{
(1) splash screen (1) split pdf (1) test score (1) text
animation (1) text editor (1) text to pdf converter (1) text
public void mousePressed(MouseEvent e){ to word converter (1) textarea (1) textfield (1)
Color color=rb.getPixelColor(e.getX(),e.getY()); //get the color at the clicked point textlistener (1) thread (1) transparent (1) transparent
try{ window (1) upload file (1) video (1) video player (1)
setColor(color); //take the color at the clicked point for later use word to pdf converter (1) word to text converter (1) xml
if(actionDraw){ //add text to the update image processing (1) zip file (1) zoom (1)

if(actionSlided || actionResized || actionTransparent || actionRotated || drawn)


addTextToImage(e.getX()-x,e.getY()-y, bimg);
POPULAR POSTS
else //add text to the original image
addTextToImage(e.getX()-x,e.getY()-y, orBufferedImage); REFERENCES
Quiz
progr Apache POI
am
Apache tika
This
} FontBox
is a
quiz program . The IText
}catch(Exception ie){} program allows you
to answer up to 10 Java API
Java programming documentation
basic questions. JMF
} Then it displays a
report that shows Joda-time
al... Jsoup
} JTidy
Fracti
ons PdfBox
//The KList class extends the KeyAdpater class to implement the keyPressed method Calcu
PdfRenderer
//to handle the key event of the Canvas lator
class KList extends KeyAdapter{ progr XMLWorker
am
public void keyPressed(KeyEvent e){
The
if(e.getKeyCode()==27){ //ESC is pressed to stop drawing the text on the image FractionCalculator
actionDraw=false; program is able to
textToDraw=""; add, subtract,
fontName=""; multiply, and divide
two fractions. The
fontSize=0; program asks the
} user to choose one
} of the ...
}
//The addTextToImage method adds the text specified by the user to the image Imag
e
public void addTextToImage(int x,int y, BufferedImage img){ Editor
//create a blanck buffered image The
BufferedImage bi=(BufferedImage)createImage(img.getWidth(),img.getHeight()); Imag
//create the Graphics2D object from the buffered image eEditor program is
Graphics2D g2d=(Graphics2D)bi.createGraphics(); a simple program
that can help you to
//Set the font of drawing pen write Java code to
g2d.setFont(new Font(fontName,Font.BOLD,fontSize)); edit image or photo
//Set the pen color file. This image
g2d.setPaint(colorTextDraw); editor program can
...
//Draw the image on the blank buffered image
g2d.drawImage(img,0,0,null);
//Draw the text on the buffered image YOU MAY ALSO LIKE THE FOLLOWINGS
g2d.drawString(textToDraw,x,y);
Android apps development in Java
//update the image
bimg=bi; J2ME
//there is a text drawing on the image Java exercises and solutions
drawn=true; Java tips
//clean the Graphics2D object Java tutorials
g2d.dispose();
JSP
//redisplay the update image so the text is displayed on the image now
repaint();
}

//set the selected color to the c variable


public void setColor(Color color){
c=color;
}
//set the image filename to the imgFileName variable
public void setImgFileName(String fname){
imgFileName=fname;
}
//initialize variables
public void initialize(){
imageLoaded=false;
actionSlided=false;
actionResized=false;
actionCompressed=false;
actionTransparent=false;
actionRotated=false;
actionDraw=false;
drawn=false;
dirHor=false;
c=null;
radian=0.0f;
e=0.0f;
}

//cancel the image editing so we reset the drawing area


public void reset(){
if(imageLoaded){
prepareImage(imgFileName);
repaint();
}

}
//Rotate the image shown on the program interface
public void makeImageRotate(BufferedImage image,int w,int h){

BufferedImage bi=(BufferedImage)createImage(w,h);
Graphics2D g2d=(Graphics2D)bi.createGraphics();
radian=(float)Math.PI/2; //angle
g2d.translate(w/2,h/2); move to coordinate (w/2,h/2)
g2d.rotate(radian); //rotate the image
g2d.translate(-h/2,-w/2); //move the coordinate back
g2d.drawImage(image,0,0,null); //draw the rotated image
bimg=bi; //update the image so now you see the rotated image
g2d.dispose();

}
//The rotateImage invokes the makeImageRotate method to rotate the image
public void rotateImage(){
BufferedImage bi;
//rotate update image
if(actionSlided || actionResized || actionTransparent || actionRotated || drawn){
bi=bimg;
}
//rotate the original image
else{
bi=orBufferedImage;
}

makeImageRotate(bi,bi.getHeight(),bi.getWidth());

actionRotated=true; //set the actionRotated to true to indicate that


//the image is rotated
repaint(); //repaint the update image

}
//The makeCompression method has code to compress the image
//In java, you can specify the compression quality value by using the IIOImage class
public void makeCompression(File outFileName){
try{
ImageWriter imgWriter =(ImageWriter)
ImageIO.getImageWritersByFormatName("jpg").next();

//Create image output stream objects from the image files


ImageOutputStream imgOutStrm =
ImageIO.createImageOutputStream(outFileName);

//Set the image output stream object to the writer


imgWriter.setOutput(imgOutStrm);

//wrap the image data (read from the file) in IIOImage object
IIOImage iioImg;
if(actionSlided || actionResized){ //bimg not a blank buffered image
iioImg = new IIOImage(bimg, null,null);
}
else{
iioImg = new IIOImage(orBufferedImage, null,null); //otherwise compress the original
buffered image
}

//Create paramter for image writer


ImageWriteParam jpgWriterParam = imgWriter.getDefaultWriteParam();

//Set compresson mode


jpgWriterParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);

//Set compression quality


jpgWriterParam.setCompressionQuality(0.7f);

//Write the image with specified parameters to the file


imgWriter.write(null, iioImg, jpgWriterParam);

//clean objects
imgOutStrm.close();
imgWriter.dispose();
}catch(Exception e){}

}
//The resizeImage method has code to resize the image
//This method is invoked when the user clicks OK button on the image resize window
//The image resize window is displayed when you select the Image resize sub-menu
item
public void resizeImage(int w,int h){
BufferedImage bi=(BufferedImage)createImage(w,h);
Graphics2D g2d=(Graphics2D)bi.createGraphics();
//resize the update image

if(actionSlided || actionTransparent || actionRotated ||drawn)


g2d.drawImage(bimg,0,0,w,h,null);
//resize the original image
else
g2d.drawImage(orImg,0,0,w,h,null);
bimg=bi;
g2d.dispose();

//Prepare the image so it is ready to display and editable


public void prepareImage(String filename){
initialize();
try{
//track the image loading
mt=new MediaTracker(this);
orImg=Toolkit.getDefaultToolkit().getImage(filename);
mt.addImage(orImg,0);
mt.waitForID(0);
//get the image width and height
int width=orImg.getWidth(null);
int height=orImg.getHeight(null);
//create buffered image from the image so any change to the image can be made
orBufferedImage=createBufferedImageFromImage(orImg,width,height,false);
//create the blank buffered image
//the update image data is stored in the buffered image
bimg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
imageLoaded=true; //now the image is loaded
}catch(Exception e){System.exit(-1);}
}

//The filterImage method applies brightness to the image when the knob of the image
slider is
//making changed.
//When the value of the image slider changes it affects the e variable
//so the image is brighter or darker
public void filterImage(){
float[] elements = {0.0f, 1.0f, 0.0f, -1.0f,e,1.0f,0.0f,0.0f,0.0f};
Kernel kernel = new Kernel(3, 3, elements); //create keynel object to encapsulate the
elements array
ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
//create ConvolveOp to encapsulate
//the kernel
bimg= new
BufferedImage(orBufferedImage.getWidth(),orBufferedImage.getHeight(),BufferedImag
e.TYPE_INT_RGB);
cop.filter(orBufferedImage,bimg); //start filtering the image
//the filtered image is stored in the bimg buffered image
//now the image increases or decreases its brightness

}
//set a value to e variable
//this method is invoked when the user makes change to the image slider
public void setValue(float value){
e=value;
}

//Set a boolean value the actionSlided variable


public void setActionSlided(boolean value ){
actionSlided=value;
}
//Set a boolean value the actionResized variable
public void setActionResized(boolean value ){
actionResized=value;
}
//Set a boolean value the actionCompressed variable
public void setActionCompressed(boolean value ){
actionCompressed=value;
}
//Set a boolean value the actionDraw variable
public void setActionDraw(boolean value ){
actionDraw=value;

//The createBufferedImageFromImage method is abled to generate a buffered image


from an input image
public BufferedImage createBufferedImageFromImage(Image image, int width, int
height, boolean tran)
{ BufferedImage dest ;
if(tran)
dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
else
dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = dest.createGraphics();
g2.drawImage(image, 0, 0, null);
g2.dispose();
return dest;
}

//The makeTransparency method makes the selected background area of the image
transparent
//This method works well if the background of the image has a single color value (e.g.
white, black, blue, etc.)
public void makeTransparency(final Color col){
ImageFilter filter = new RGBImageFilter() {
int imageRGB = col.getRGB();

public final int filterRGB(int x, int y, int rgb) {


if (rgb==imageRGB ) {

return 0x00FFFFFF & rgb; //make the selected color transparent


}
else {
return rgb; //nothing change to the selected color
}
}
};
ImageProducer ip;
if(actionSlided || actionResized)
ip = new FilteredImageSource(bimg.getSource(), filter);
else
ip = new FilteredImageSource(orImg.getSource(), filter);

Image img=getToolkit().createImage(ip);
try{
mt.addImage(img,0);
mt.waitForID(0);
bimg=createBufferedImageFromImage(img,img.getWidth(null),img.getHeight(null),tru
e);
actionTransparent=true;
repaint();
}catch(Exception e){}
}

//Save the image file


public void saveToFile(String filename){
String ftype=filename.substring(filename.lastIndexOf('.')+1);
try{
//save the compressed image
//we separate the compression action from other actions on the image
if(actionCompressed)
makeCompression(new File(filename));
//save the update image
else if(actionSlided || actionResized || actionTransparent || actionRotated || drawn)
ImageIO.write(bimg,ftype,new File(filename));
}catch(IOException e){System.out.println("Error in saving the file");}
}
//Assign values to the variables used in drawing text on the image
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;
}
}

////end of the ImgArea class

////start the Main class


//The Main class represents the main program interface
//In this interface, you can open the image file, save the update image, and edit the
image

class Main extends JFrame implements ActionListener{

ImgArea ia;
JFileChooser chooser;
JMenuBar mainmenu;
JMenu menu;
JMenu editmenu;
JMenuItem mopen;
JMenuItem msaveas;
JMenuItem msave;
JMenuItem mexit;
JMenuItem mbright;
JMenuItem mcompress;
JMenuItem mresize;
JMenuItem mrotate;
JMenuItem mtransparent;
JMenuItem maddtext;
JMenuItem mcancel;
String filename;
Main(){
ia=new ImgArea();
Container cont=getContentPane();
cont.add(ia,BorderLayout.CENTER );
mainmenu=new JMenuBar();
menu=new JMenu("File");
menu.setMnemonic(KeyEvent.VK_F);

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);
menu.add(mopen);
menu.add(msaveas);
menu.add(msave);
menu.add(mexit);

editmenu=new JMenu("Edit");
editmenu.setMnemonic(KeyEvent.VK_E);
mbright=new JMenuItem("Image brightness");
mbright.setMnemonic(KeyEvent.VK_B);
mbright.addActionListener(this);

maddtext=new JMenuItem("Add text on image");


maddtext.setMnemonic(KeyEvent.VK_A);
maddtext.addActionListener(this);

mresize=new JMenuItem("Image resize");


mresize.setMnemonic(KeyEvent.VK_R);
mresize.addActionListener(this);

mcompress=new JMenuItem("Image compression");


mcompress.setMnemonic(KeyEvent.VK_P);
mcompress.addActionListener(this);

mrotate=new JMenuItem("Image rotation");


mrotate.setMnemonic(KeyEvent.VK_T);
mrotate.addActionListener(this);

mtransparent=new JMenuItem("Image transparency");


mtransparent.setMnemonic(KeyEvent.VK_T);
mtransparent.addActionListener(this);

mcancel=new JMenuItem("Cancel editing");


mcancel.setMnemonic(KeyEvent.VK_L);
mcancel.addActionListener(this);

editmenu.add(maddtext);
editmenu.add(mbright);
editmenu.add(mcompress);
editmenu.add(mresize);
editmenu.add(mrotate);
editmenu.add(mtransparent);
editmenu.add(mcancel);

mainmenu.add(menu);
mainmenu.add(editmenu);
setJMenuBar(mainmenu);

setTitle("Image Editor");
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();
}

////start the ImageBrightness class


//The ImageBrightness class represents the interface to allow the user to make the
image
//brighter or darker by changing the value of the image slider
//The ImageBrightness class is in the Main class
public class ImageBrightness extends JFrame implements ChangeListener{
JSlider slider;

ImageBrightness(){
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
dispose();

}
});
Container cont=getContentPane();
slider=new JSlider(-10,10,0);
slider.setEnabled(false);
slider.addChangeListener(this);
cont.add(slider,BorderLayout.CENTER);
slider.setEnabled(true);
setTitle("Image brightness");
setPreferredSize(new Dimension(300,100));
setVisible(true);
pack();
enableSlider(false);
}
public void enableSlider(boolean enabled){
slider.setEnabled(enabled);
}
public void stateChanged(ChangeEvent e){
ia.setValue(slider.getValue()/10.0f);
ia.setActionSlided(true);
ia.filterImage();
ia.repaint();
enableSaving(true);

} ////end of the ImageBrightness class

////start the ImageResize class


//The ImageResize class represents the interface that allows you to resize the image
//by making changes to its width and height
//The ImageResize class is in the Main class
public class ImageResize extends JFrame implements ActionListener {
JPanel panel;
JTextField txtWidth;
JTextField txtHeight;
JButton btOK;
ImageResize(){
setTitle("Image resize");
//setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400,100));

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.CENTER);
setVisible(true);
pack();
enableComponents(false);
}
//This method can be invoked to enable the text boxes of image width and height
public void enableComponents(boolean enabled){
txtWidth.setEnabled(enabled);
txtHeight.setEnabled(enabled);
btOK.setEnabled(enabled);
}
//This method works when you click the OK button to resize the image
public void actionPerformed(ActionEvent e){
if(e.getSource()==btOK){
ia.setActionResized(true);
ia.resizeImage(Integer.parseInt(txtWidth.getText()),Integer.parseInt(txtHeight.getText(
)));
enableSaving(true);
ia.repaint();
}
}
//Restrict the key presses
//Only number, backspace, and delete keys are allowed
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))
{
ke.consume(); //hide the unwanted key

}
}////end of the ImageResize class

////start the TextAdd class


//The TextAdd class represents the interface that allows you to add your text to the
image
//In this interface you can input your text, select color, font name, and font size of the
text
//The TextAdd class is in the Main class
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");
//setDefaultCloseOperation(EXIT_ON_CLOSE);
setPreferredSize(new Dimension(400,150));

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

btSetColor=new JButton("Set 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){ //the button OK is clicked so the text is ready to place on the
image
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){ //show color chooser dialog for color selection
JColorChooser jser=new JColorChooser();
colorText=jser.showDialog(this,"Color Chooser",Color.BLACK);

}
}

//The listFonts method get all available fonts from the system
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);

}
} ////end of the TextAdd class

//handling events of sub-menu items on the main program interface


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)
{
new TextAdd();
}

else if(source.getText().compareTo("Image brightness")==0)


{

ImageBrightness ib=new ImageBrightness();


if(ImgArea.imageLoaded)
ib.enableSlider(true);
}
else if(source.getText().compareTo("Image compression")==0)
{
if(ImgArea.imageLoaded){
ia.setActionCompressed(true);
enableSaving(true);
}
}

else if(source.getText().compareTo("Image resize")==0)


{

ImageResize ir=new ImageResize();


if(ImgArea.imageLoaded)
ir.enableComponents(true);
}
else if(source.getText().compareTo("Image rotation")==0)
{

if(ImgArea.imageLoaded){
ia.rotateImage();
enableSaving(true);
}
}

else if(source.getText().compareTo("Image transparency")==0){


if(ImgArea.c==null){
JOptionPane dialog=new JOptionPane();
dialog.showMessageDialog(this,"Click the background area of the image
first","Error",JOptionPane.ERROR_MESSAGE);
}
else if(ImgArea.imageLoaded){
ia.makeTransparency(ImgArea.c);
enableSaving(true);
}
}

else if(source.getText().compareTo("Cancel editing")==0) {


ia.setImgFileName(filename);
ia.reset();
}

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

//The setImage method has code to open the file dialog so the user can choose
//the file to show on the program interface
public void setImage(){

int returnVal = chooser.showOpenDialog(this);


if(returnVal == JFileChooser.APPROVE_OPTION) {
filename=chooser.getSelectedFile().toString();
ia.prepareImage(filename);
}

//The showSaveFileDialog method has code to display the save file dialog
//It is invoked when the user select Save as... sub-menu item
public void showSaveFileDialog(){
int returnVal = chooser.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION) {
String filen=chooser.getSelectedFile().toString();
ia.saveToFile(filen);

}
}

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

} ////end of the Main class

public class ImageEditor{

public static void main(String args[]){


new Main();

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

Posted by Dara Yuk


Labels: image editor, Java, program, source code

34 comments:

Anonymous September 25, 2013 at 5:26 AM


Please say right or wrong. After reading this example program, i learn that to edit an
image in Java such as changing size, brightness, rotating, ...firstly, the image file must
be converted to the BufferedImage object. What i am not sure is why do you use the
MediaTracker?
Reply

Replies

RAJ SINGH January 22, 2017 at 1:14 AM


LINE 182 GENERATES ERROR

Reply

Dara Yuk September 26, 2013 at 5:41 AM


Yes, you are right.
The size of an image might be big so that it is time consuming to load the data of the
image. The MediaTracker class is used to track the loading process. It makes sure the
the image is loaded completely before sending the image to subsequent code.
Reply

Replies

Anonymous March 28, 2017 at 6:04 AM


i want to add feature of change color of image in gray ,red ,green and blue.plz
hel me...

Reply

chandraprakash chaurasiya February 10, 2014 at 4:57 AM


hello friend... can you please help me little in my image processing project?
i have very less time for submisson....
plz help me....
Reply

Irika April 25, 2014 at 11:38 PM


Its my pleasure that I've stopped by here and come to know about image editor program
and I hope that in such knowledge would be sound good for me. Thanks dude :)
Reply

Mayur Chithore June 10, 2014 at 2:09 AM


Hey Dara...can u tell me the mechanism to add cropping into this program.I tried lot. But
its giving me lot of errors.it is your program. So can u help me out? I really needed it.
Here is my id: mayurchithore@gmail.com
Reply

Sam Sharma July 10, 2014 at 9:08 PM


Sir Will you please send me your Full code on Image Editor in Java :)
Reply

Firmansyah Destyan December 3, 2014 at 11:22 PM


Sir. Can u help me. How to add another feature ex: contrast, zoom etc
Reply

krishanlakhiwal August 19, 2015 at 6:37 AM


hey man i need help with your code. i am supposed to submit an image editing java
program to my college as part of my industrial training but there is not much time to learn
everything related to image editing.I was actually thinking of using your code for the
project. i have edited your code a little bit i.e. i have removed "compression" and
"transparency" option from the code. but since i dont know much about your code so is it
possible if could explain the basics of your code or may be make a video tutorial about
this code that might help me understanding it.. it would be really great if you could do
that... thankx in advance...
Reply

Fixx Group October 1, 2015 at 12:40 AM


Thanks for posting.

Image editing solutions


Reply

jaknap March 4, 2016 at 1:39 AM


not good plz improve this code
Reply

Yuga Bharathi March 21, 2016 at 1:27 AM


Nice post. I learned something new. Thanks for sharing.
clipping path services
Reply

Replies

Susan Manzano March 31, 2016 at 1:17 AM


Thank you, Yuga, my dear! You know, I don't like to use Java image editors. It
is better to use something like adobe for photo processing or
https://macphun.com/ for Mac users.

Matt Witz May 20, 2016 at 7:15 AM


That's not what this program is for. The GUI is for the user to test out what
each feature does, but this class is truly written to help the user implement its
abilities into the rest of his program by accessing its methods.

Reply

Matt Witz May 20, 2016 at 7:09 AM


Hey on line 182 the comment isn't actually made a comment with "//" -- this creates an
error. Also, people are going to be using this in projects that are already pretty large, yet
this program alone imports 12 large java projects. That's huge. Can you guys cut down
on that? I may reupload this here if I ever get to fixing it.
Reply

Replies

Matt Witz May 20, 2016 at 7:11 AM


Also is there some kind of API for this class? It's a bit annoying to have to sift
through everything when the creator can simply write up here (even if only in
the comments) exactly what each method does and its parameters.

Reply

prathap kumar May 20, 2016 at 9:12 AM


Java Training in Chennai | Core Java Training in Chennai

Online Java Training | Java EE Training Institute in Chennai


Reply

http://forseoblogger.blogspot.com/2016/07/high-pr-image-sharing-sites-
list.html July 23, 2016 at 6:06 AM
Thanks for sharing this post
Reply

ybr (alias ybrao a donkey) August 15, 2016 at 9:43 AM


g2d.translate(w/2,h/2); move to coordinate (w/2,h/2). NEEDS to be corrected as //move
to coordinate (w/2,h/2). Kinly add // in your code at that particular place.
2) In text add: Can we make the text to line wrap? We have to add one line of code, I
believe. 3) A Control Z keyboard shortcut for cancel edit, if possible.
Reply

al December 18, 2016 at 6:21 AM


how do I add a color conversion function for this program?
Reply

Ann Lily January 19, 2017 at 11:05 PM


You need to kill time, you'd have time to look these kids active. Refer to our website.
Hope you get the most comfort.
Thanks for sharing ! word cookies game | hill climb racing 2
Reply

nikhil bisht January 25, 2017 at 6:35 AM


how to create image area?, i have problem in understanding the code
Reply

Anonymous March 2, 2017 at 1:56 AM


Setup of image editor
Reply

Jane March 11, 2017 at 10:17 PM


It is really a vector way that is used for isolating the items from the foundation. Photo
Masking
Reply

nikhil bisht March 12, 2017 at 8:32 AM


ia.setValue(slider.getValue()/10.0f);
can someone explain this?
Reply

James harper May 19, 2017 at 6:15 PM


Many of these sites are very user-friendly and you perform the editing tasks on the web
without needing to download software. Product photo editing

Reply

Ella lily May 21, 2017 at 4:49 PM


Discolored or darkened photos get a fresh lease of life with these techniques. Your old
photographs will look like new after professional colorization. Neck joint service
Reply

Anonymous July 7, 2017 at 2:43 AM


Hii..
I was trying to add some filters like sepia,black n white etc to this code..everything is
working fine but when i click 'cancel editing' option whole image turns black instead of
original image only for those new filters...can anybody help????
I need to do this ASAP.
Reply

Replies

Suraj Rimal August 27, 2017 at 9:46 AM


hi can you please send me your code? email daidparkedme@gmail.com
thank you

Reply

robb September 8, 2017 at 7:58 AM


love such minimalistic photos, especially in white/black processing. sometimes its useful
to enhance photo right before creating new work. for example https://photolemur.com
Reply

Ashley October 24, 2017 at 7:01 AM


One of the most established propelled photo editing procedures being utilized by
photographers and even by those simply fiddling with photography is photo control.visit
us
Reply

Martina December 8, 2017 at 1:08 AM


One of the immense advantages if needing to attempt this bit of programming is its free
trial form. https://photolemur.com
Reply

Philip T. Greene December 9, 2017 at 2:32 AM


You can use Photoshop in making proficient images; as well as be used to make
entertaining photograph impacts and make our dull images spring up. Product Photo
Retouching
Reply

Enter your comment...

Comment as: Select profile...

Publish Preview

Links to this post

Newer Post Home Older Post

ABOUT ME
Hi, my name is Yuk Sovandara. I am an IT officer and lecturer. In my free time, I like to write something about programming. In 2011, i created a
website www.worldbestlearningcenter.com that provides free tutorials, exercises, and tips of the most popular programming and web scripting
languages. Seven months ago i created the javatheprogram.blogspot.com blog providing Java tutorials and example programs. Recently, i also
created a blog called dev-androidapps.blogspot.com for people who want to become Android developers by learning from example programs. To
contact me, please email yuk.dara@gmail.com. You also can connect with me on Facebook , and Google+.

TRANSLATE

Select Language

Powered by Translate

Copyright © javatheprogram.blogspot.com 2013. All rights reserved. Picture Window theme. Powered by Blogger.

Вам также может понравиться