Showing posts with label Java program. Show all posts
Showing posts with label Java program. Show all posts

Saturday, June 1, 2013

JPEG Converter

The JPEGConverter program allows you to convert different image formats:
-jpeg to png, bmp, and gif
-png to jpeg, bmp, and gif
-bmp to jpeg, png, and gif
-gif to jpeg, png, and bmp.

The main class used in the image conversion is ImageIO. To convert a from an image format to another, firstly you need to transform the original image to an buffered image. Then use the write method of the ImageIO to write the buffered image to destination image format.

Jpeg converter in Java

JPEGConverter source code:

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

class DrawImage extends Canvas implements ImageObserver{
   
Dimension ds;
String filename;
BufferedImage bi;

DrawImage(){
ds=getToolkit().getScreenSize(); //get the screen size-width and height
filename=null; //initialize the image file name

}

public void paint(Graphics g){

if(filename!=null){
try{
bi=ImageIO.read(new File(filename)); //read the image file
}catch(IOException ie){}
drawIt(g,bi); //invoke the drawIt method to display the image
}

    }

//The drawIt method has code to draw the image on the Canvas drawing object
public void drawIt(Graphics g, BufferedImage img){

Graphics2D g2d=(Graphics2D)g; //create graphics2d object
int w=img.getWidth(this); //get the image width
int h=img.getHeight(this);//get the image height
int mX=(int)ds.getWidth()/2-img.getWidth(this)/2; //x-axis to move the origin x-axis from
int mY=(int)ds.getHeight()/2-img.getHeight(this)/2;//y-axis to move the origin y-axis from
g2d.translate(mX,mY); //move the origin coordinate to the coordinate (mX,mY)
g2d.drawImage(img,0,0,w,h,this);//display the image

}

//The selecteFile method displays the file chooser dialog for image file selection
public void selectFile(){
JFileChooser chooser = new JFileChooser(); //create file chooser object
//create FileNameExtensionFilter object to filter the image files
    FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG, BMP, GIF, PNG Images", "jpg", "bmp","gif","png");
    chooser.setFileFilter(filter);
    chooser.setMultiSelectionEnabled(false); //disable multi-selection
    int returnVal = chooser.showOpenDialog(this); //show the file chooser dialog
    if(returnVal == JFileChooser.APPROVE_OPTION) {
filename=chooser.getSelectedFile().toString(); //ge the selected file path
           
        }
}

//get the image file name
public String getFileName(){
return(filename);
}

//convert from an input image format to the selected image format
public void convert(String toFormat){
try{
File outf=new File(filename.substring(0,filename.lastIndexOf('.')+1)+toFormat);
ImageIO.write(bi,toFormat,outf);
}catch(Exception e){System.out.println("Error...");}


}



}

//The ShowProgram class represents the main interface of the JPEGConverter program
//The program has a menu bar that contains two menus: File and Convert to
//In File menu, you can open the image file and exit the program
//In the Convert to menu, you can convert the image from an input format to another
class  ShowProgram extends JFrame implements ActionListener{

JButton btconvert;
JPanel panel;
DrawImage di;
JMenuBar mainmenu;
JMenu menufile;
JMenu menuconvert;

ShowProgram(){
setTitle("Image Converter");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH);

mainmenu=new JMenuBar();
menufile=new JMenu("File");
JMenuItem mopen=new JMenuItem("Open...");
mopen.setMnemonic(KeyEvent.VK_O);
mopen.addActionListener(this);
JMenuItem mexit=new JMenuItem("Exit");
mexit.setMnemonic(KeyEvent.VK_X);
mexit.addActionListener(this);
menufile.add(mopen);
menufile.add(mexit);

menuconvert=new JMenu("Convert to");
JMenuItem mjpg=new JMenuItem("JPG");
mjpg.setMnemonic(KeyEvent.VK_G);
mjpg.addActionListener(this);

JMenuItem mbmp=new JMenuItem("BMP");
mbmp.setMnemonic(KeyEvent.VK_B);
mbmp.addActionListener(this);

JMenuItem mgif=new JMenuItem("GIF");
mgif.setMnemonic(KeyEvent.VK_F);
mgif.addActionListener(this);

JMenuItem mpng=new JMenuItem("PNG");
mpng.setMnemonic(KeyEvent.VK_P);
mpng.addActionListener(this);

menuconvert.add(mjpg);
menuconvert.add(mbmp);
menuconvert.add(mgif);
menuconvert.add(mpng);

mainmenu.add(menufile);
mainmenu.add(menuconvert);

setJMenuBar(mainmenu);

btconvert=new JButton("Convert");
btconvert.setBackground(Color.YELLOW);
btconvert.addActionListener(this);
btconvert.setEnabled(true);

di=new DrawImage();
add(di,BorderLayout.CENTER );
setVisible(true);
menuconvert.setEnabled(false);
}

//define actions for menu selections
public void actionPerformed(ActionEvent e) {

JMenuItem source = (JMenuItem)(e.getSource());
if(source.getText().compareTo("Open...")==0)
{
di.selectFile(); //display file chooser dialog box
di.repaint(); //repaint the drawing area
if(!di.getFileName().equals(""))
menuconvert.setEnabled(true); //enable image conversion sub-menu items
}
else if(source.getText().compareTo("Exit")==0)
System.exit(0);
else
di.convert(source.getText()); //convert the image to different format


}



}

public class JPEGConverter{

public static void main(String args[]){
     new ShowProgram(); //display the program interface
 
}


}

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.

Tuesday, May 21, 2013

Compress image


The ImageCompressor program can be useful for you  to compress images. You can make the image smaller in size and at the same time its original quality reduces little. You need to use the IIOImage class to set the compress quality of the image.

ImageCompression source code:

import javax.imageio.*;
import javax.imageio.stream.*;
import java.io.*;

public class ImageCompressor{

public static void main(String[] args)  throws Exception{
try{
makeCompression(args[0],args[1]);

}catch(ArrayIndexOutOfBoundsException aie){showMessage();}

}

public static void makeCompression(String inFileName,String outFileName)  throws Exception{

1 ImageReader imgReader = (ImageReader)ImageIO.getImageReadersByFormatName("jpg").next();
2 ImageWriter imgWriter =(ImageWriter) ImageIO.getImageWritersByFormatName("jpg").next();
3 ImageInputStream imgInputStream = ImageIO.createImageInputStream(new File(inFileName));
4 ImageOutputStream imgOutputStream = ImageIO.createImageOutputStream(new File(outFileName));
5 imgReader.setInput(imgInputStream);
6 imgWriter.setOutput(imgOutputStream);
7 IIOImage iioImg = new IIOImage(imgReader.read(0), null,null);
8 ImageWriteParam jpgWriterParam = imgWriter.getDefaultWriteParam();
9 jpgWriterParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
10 jpgWriterParam.setCompressionQuality(0.7f);
11 imgWriter.write(null, iioImg, jpgWriterParam);
//clean objects
imgInputStream.close();
imgOutputStream.close();
imgWriter.dispose();
imgReader.dispose();
}

public static void showMessage(){
System.out.println("Invalid files input! Please run the program in the form below:");
System.out.println("java ImageCompressor input_image_file output_image_file");
}
}

Size of original image is  108 KB.

image size before compression

 Size of the compressed image is 47.9 KB.

image size after compression




Code Explanation
1 Create a image reader object to read JPG image file.
2 Create a image writer object to write JPG image to an output file.
3 Create an image input stream object to be used for image stream reading.
4 Create an image output stream object to be used for image stream writing.
5 Set the image input stream object to the image reader object so it is ready to retrieve the image stream.
6 Set the image output stream object to the image writer object so it is ready to write the image stream to an output file.
7 Wrap the image stream in IIOImage object so you can specify the compression settings.
8 Create the image writer parameter object.
9 Set the compression mode to the image stream. It is to control the compression settings. Java provides four compression modes: MODE_COPY_FROM_METADATA, MODE_DEFAULT , MODE_DISABLED , and MODE_EXPLICIT.
10 Set the compression quality to the image stream. The compression quality value is in the range of 0.0 to 1.0. The 0.0 value means high compression so it is  the lowest quality compression. The value 1.0 is for
lowest compression so it is the highest quality image compression.
11 Write the image stream with the compession settings that contains in IIOImage object to the output file.

Monday, May 20, 2013

Screen capture


The ScreenCapture is a program that enables you to capture your computer on screen activities. The captured images of the screen are stored in a folder called tempDir. It is easy to capture your screen with ScreenCapture. When the program opens you can click the Start Capture to begin the screen capture task. When you want to stop the capturing task, click Stop Capture.

Screen Capture in Java


ScreenCapture source code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import javax.imageio.*;
import java.awt.image.*;

class ScreenCapture extends JFrame implements ActionListener{
  JButton btCap;
Robot rb;
boolean capturing=true;
CaptureControl cc;
ScreenCapture() throws AWTException{

setTitle("Screen Capture");
setIconImage(getToolkit().getImage("icon.png"));
setPreferredSize(new Dimension(300,60));

btCap=new JButton("Start Capture");
btCap.addActionListener(this);
add(btCap,BorderLayout.CENTER);

setResizable(false);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
pack();
rb=new Robot(); //create Robot object used in capture

}


public void actionPerformed(ActionEvent e){
try{
if(btCap.getText().equals("Start Capture")){ //start capturing the screen
btCap.setText("Stop Capture");
setState(ICONIFIED);
cc=new CaptureControl();
cc.start();
}
else if(btCap.getText().equals("Stop Capture")){ //stop capturing the screen
cc.stopCapture();
btCap.setText("Stop Capture");

}

}catch(Exception ee){}



}



class CaptureControl extends Thread{
boolean started;
File tempDir;
Dimension ds;
CaptureControl (){
started=true;
tempDir=new File("tempDir");
if(!tempDir.exists())
1 tempDir.mkdir();
2 ds=getToolkit().getScreenSize();
}

public void run(){
try{
while(started){
3 BufferedImage bi=rb.createScreenCapture(new Rectangle(ds));
4 ImageIO.write(bi,"jpg",new File(tempDir.getAbsolutePath()+"/"+System.currentTimeMillis()+".jpg"));
5 Thread.sleep(100);
}

}catch(Exception ie){}
}


public void stopCapture(){
started=false;

}


}



public static void main(String args[])  throws Exception{
   
new ScreenCapture();
 
               }


}


Code Explanation
1 Create the tempDir folder to store the captured images.
2 Get the dimension of the screen so you are able to capture the full screen.
3 Capture the screen by using the createScreenCapture of the Robot rb object. The result of each capture is a BufferedImage object.
4 Write the BufferedImage object bi to a file.
5 The interval or time delay between each capture action is 100 milliseconds. The program continues to capture the screen while there is no interruption. To interrupt or stop the capturing task, you will click Stop Capture.

Saturday, May 18, 2013

Image brightness


The ImageBrightness program allows you to selection an image file. When the image displays on the program window you can slide the knob  left or right to change the brightness of the image. After you make change to the image, you can save the updated image in a separated file or override the original image file.

ImageBrightness source code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.image.*;
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{
                        Image orImg;
                        BufferedImage orBufferedImage;
                        BufferedImage bimg;
                        float e=0.0f;
                        Dimension ds;
                        int mX;
                        int mY;
                        int x;
                        int y;
                        boolean imageLoaded;
                        boolean actionPerf;

                        public ImgArea(){
                                    imageLoaded=false;           
                                    actionPerf=false;
                        }
                       
1                      public void paint(Graphics g){
                                    Graphics2D g2d=(Graphics2D)g;                        
                                    g2d.translate(mX,mY);
                                    if(imageLoaded){ //the image loaded
                                                if(actionPerf) //the image have been changed
                                                            g2d.drawImage(bimg,x,y,this);
                                                else
                                                            g2d.drawImage(orBufferedImage,x,y,this);
                                    }
                                    g2d.dispose(); //clear graphics object
                                   
                        }

2                      public void prepareImage(String filename){

                                    try{
                                    MediaTracker mt=new MediaTracker(this);//Create MediaTracker object
                                    //to track the image load                             
                                    orImg=Toolkit.getDefaultToolkit().getImage(filename); //read the image file
                                    mt.addImage(orImg,0);//add image to the tracker
                                    mt.waitForID(0);        //wait for the image to fully load                
                                    if(orImg==null) System.exit(-1); //if no valid image selected exit the program
                                    ds=getToolkit().getScreenSize(); //get the size of screen
                                    //new coordinate to move the original coordinate to                             
                                    mX=(int)ds.getWidth()/2;
                                    mY=(int)ds.getHeight()/2;
                                    //coordinate to show the image on the screen
                                    x=-orImg.getWidth(this)/2;
                                    y=-orImg.getHeight(this)/2;
                                    //get the size of the orignal image
                                    int width=orImg.getWidth(null);
                                    int height=orImg.getHeight(null);
                                    //Create BufferedImage object from the original image
                                    orBufferedImage=createBufferedImageFromImage(orImg,width,height);
                                    //Create the blank BufferedImage object                        
                                    bimg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);          
                                    imageLoaded=true; //now the image loaded
                                    }catch(Exception e){System.exit(-1);}
                        }

3                      public void filterImage(){
                                    //Define elements array used for Kernel object
                                    float[] elements = {0.0f, 1.0f, 0.0f, -1.0f,e,1.0f,0.0f,0.0f,0.0f};
                                    //create Kernel object kernel from the elements array
                                    Kernel kernel = new Kernel(3, 3, elements);
                                    //Create ConvolveOp object cop to wrap the kernel object
                                    ConvolveOp cop = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
                                    //filtering the image
                                    //destination image is placed in BufferedImage object bimg for later showing and saving
                                    cop.filter(orBufferedImage,bimg);
                                   
                        }

4                      public void setValue(float value){
                                    e=value;
                        }

5                      public void setActionPerf(boolean value ){        
                                    actionPerf=value;
                        }
                       

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

7          public void saveToFile(String filename){
                        String ftype=filename.substring(filename.lastIndexOf('.')+1); //get file extension
                        try{
                                    if(actionPerf) //there is a change to the image so save it
                                                ImageIO.write(bimg,ftype,new File(filename));
                           }catch(IOException e){System.out.println("Error in saving the file");}
                        }
}

class  Main extends JFrame implements ChangeListener, ActionListener{
           
            JSlider jsd;
            ImgArea ia;
            JFileChooser chooser;
            JMenuBar mainmenu;
            JMenu menu;
            JMenuItem mopen;
            JMenuItem msaveas;
            JMenuItem msave;
            JMenuItem mexit;    
            String filename;
            boolean actionPerf;
            Main(){
                        ia=new ImgArea();
                        jsd=new JSlider(-10,10,0); 
                        jsd.setEnabled(false);
                        Container cont=getContentPane();
                        jsd.addChangeListener(this);
                        cont.add(ia,BorderLayout.CENTER );
                        cont.add(jsd,BorderLayout.SOUTH);       

                        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);
                        mainmenu.add(menu);
                        setJMenuBar(mainmenu);
           
                        setTitle("Image Brightness");
                        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);
                        }

8          public void actionPerformed(ActionEvent e){

                        JMenuItem source = (JMenuItem)(e.getSource());
                        if(source.getText().compareTo("Open...")==0) //The Open sub-menu item is selected
                                                {
                                                setImage();
                                                ia.repaint();
                                                      validate();
                                                                       
                                                            }
                        else if(source.getText().compareTo("Save as...")==0) //The Save as sub-menu item is selected
                                                {
                                                showSaveFileDialog();      
                                                                       
                                                            }
                        else if(source.getText().compareTo("Save")==0) //The Save sub-menu item is selected
                                                {
                                                           
                                                ia.saveToFile(filename);                
                                                            }
                       
                        else if(source.getText().compareTo("Exit")==0) //The Exit sub-menu item is selected
                                                System.exit(0);
                                                           
                                               
                        }          
                       

9          public void setImage(){
                       
                        int returnVal = chooser.showOpenDialog(this);
                        if(returnVal == JFileChooser.APPROVE_OPTION) {                           
                                    filename=chooser.getSelectedFile().toString();
                                    ia.prepareImage(filename); //prepare image for show
                                    jsd.setEnabled(true); //enable the slider
                                    jsd.requestFocus(); //move focus to the slider
                                                }
                                
                        }

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

11        public void stateChanged(ChangeEvent e){
                        ia.setValue(jsd.getValue()/10.0f);
                        ia.filterImage();
                        ia.repaint();
                        ia.setActionPerf(actionPerf=true);//tells the ImgShow object that there is any change to the image
                        enableSaving(true); //enable Save as... and Save sub-menu items
                        }

12        public void enableSaving(boolean f){
                        msaveas.setEnabled(f);
                        msave.setEnabled(f);         
                       
            }

}

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


}

Image brightness or brighter in Java




Code Explanation:
1 The paint method of the Canvas class has code to display the image.
2 The prepareImage method has code to read the image file, track its loading, define coordinates to
move the original coordinate to and to show the image on the screen, create BufferedImage object from
the original image, and to create a blank BufferedImage object to be the result image of making change to the
original image.
3 The filterImage method is implemented to transfer the result image or updated image to the BufferedImage  object bimg for later showing and saving.
4 The setValue method has code to assign the value of the slider to the e variable of the ImgArea class. This value is used in the elements array that is used to construct the kernel object for image filtering process.
5 The setActionPerf method has code to assign the boolean value true or false to the actionPer variable of ImgArea class to indicate any change been made to the image.
6 The createBufferedImageFromImage has code to create an BufferedImage object from the original image.
7 The saveToFile method is invoked when the user select Save as... or Save sub-menu item to save the updated image to you current working folder.
8 The actionPerform method of the ActionListener interface is rewritten to enable menu items selection and do the action accordingly.
9 The setImage method displays the open file dialog for image file selection. The selected image file will be sent to ia object(created from ImgArea class) for showing on the screen.
10 The showSaveDialog is invoked when the user selects Save as.. sub-menu item. Its displays the save file
dialog so the user can save the updated image in a separed file.
11 The stateChanged method of the ChangeListener interface is rewritten to track any change made to the original image.
12 The enableSaving method is invoked to enable or disable the sub-menu items: Save as... or Save. When
the program firstly loads and there is no change to the image, they are disabled. They are reenabled after
any change to the image.

For more detain code explanation, please read the comments in code of the program.