Thursday, May 9, 2013

Image resize

This is a program to resize the image. The program allows you to select an image file. When the image displays on the program window, you can input the new width and height of the image in the text boxes to resize the image. If you click the Ok button, the resized image saved in a separated file in the current folder.

image resize in Java

ImageResize 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 javax.imageio.*;
import java.awt.geom.*;
import java.util.*;

class ImageArea extends Canvas implements ImageObserver{
            BufferedImage img;
            Dimension ds;
            static String filename;
            int w;
            int h;
1                      ds=getToolkit().getScreenSize();
2          public void paint(Graphics g){
                                                int x=-w/2;
                                                int y=-h/2;

3          public void setImageWidth(int width){
4          public void setImageHeight(int height){

5          public void drawIt(Graphics g, BufferedImage img,int x,int y){
                        Graphics2D g2d=(Graphics2D)g;
                        int mX=(int)ds.getWidth()/2;
                        int mY=(int)ds.getHeight()/2;                     
                        g2d.translate(mX,mY); //move the coordinate
                        g2d.drawImage(img,x,y,w,h,this); //draw the image
6          public void setImageData(BufferedImage bi){

7          public void saveResizedImage(){
                        BufferedImage bi=(BufferedImage)createImage(w,h); //create empty BufferedImage object
                        Graphics2D g2d=(Graphics2D)bi.createGraphics(); //Create the Graphics2D object from the BufferedImage object
                        g2d.drawImage(img,0,0,w,h,this); //draw the current resized image on the BufferedImage object
                        Calendar cd=Calendar.getInstance();
                        String resizedFileName=new String(cd.getTimeInMillis()+".jpg");
                        ImageIO.write(bi,"jpg",new File(resizedFileName)); //save the resized image file
                        }catch(IOException e){System.out.println("Error in saving the file...");}

8 class  Show extends JFrame implements ActionListener{
            JPanel panel;
            JButton btOK;
            JTextField txtWidth;
            JTextField txtHeight;
            ImageArea ia;
            BufferedImage bi;
                        setTitle("Image resize");
                        setExtendedState(this.getExtendedState() | this.MAXIMIZED_BOTH);
                        JMenuBar mainmenu=new JMenuBar();
                        JMenu menu=new JMenu("File");
                        JMenuItem mopen=new JMenuItem("Open...");
                        JMenuItem mexit=new JMenuItem("Exit");
                        ia=new ImageArea();
                        add(ia,BorderLayout.CENTER );  
                        btOK=new JButton("OK");
                        btOK.setToolTipText("Save the resized image file");
                        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(new JLabel("Height:"));
                        add(panel, BorderLayout.SOUTH);
9          public void actionPerformed(ActionEvent e){
                                    else {

                                                JMenuItem source = (JMenuItem)(e.getSource());
                                                                                    validate();//make sure the components display correctly
                                                else if(source.getText().compareTo("Exit")==0)

10 public void activateControls(boolean f){

11 public class KeyList extends KeyAdapter{
              public void keyTyped(KeyEvent ke){
                        char c = ke.getKeyChar(); //get the character pressed
                        int intkey=(int)c; //the character code
                        if(!(intkey>=48 && intkey<=57 || intkey==8 || intkey==127))
                                    ke.consume(); //hide the key
            public void keyReleased(KeyEvent e){
                        //the image resizes when the key released
                        if(!txtWidth.getText().equals("") && !txtHeight.getText().equals("")){
12 public void setImage(){
                        JFileChooser chooser = new JFileChooser(); //create file chooser object
                        FileNameExtensionFilter filter = new FileNameExtensionFilter("Image files", "jpg", "gif","bmp","png"); //create filter object
                        chooser.setFileFilter(filter); //apply the file filter to the file chooser object
                        chooser.setMultiSelectionEnabled(false); //only one file is selected at once
                        int returnVal = chooser.showOpenDialog(this); //show the file chooser dialog
                        if(returnVal == JFileChooser.APPROVE_OPTION) {                           
                                    String filename=chooser.getSelectedFile().toString(); //get selected file path
                                    prepareImage(filename); //invoke the prepareImage method to send image width, height, and data to the ShowArea class
13 public void prepareImage(String filename){
               File(filename)); //read the image data
                        ia.setImageData(bi); //send the image data to the ShowArea class
                        ia.setImageWidth(bi.getWidth()); //send the image width to the ShowArea class
                        ia.setImageHeight(bi.getHeight());//send the image height to the ShowArea class
                        catch(IOException e){System.out.println("Problem to load the image file...");}
                        catch(NullPointerException e){System.out.println("You may select invalid image file...");}

public class ImageResize{
            public static void main(String args[]){
                        new Show();


Code Explanation
1 Get the width and height of the computer screen.
2 The paint method of the Canvas class is invoked automatically when the Canvas object is created. It invokes the drawIt method to draw the image at the specified location.
3 The setImageWidth is used to set the width of the image.
4 The setImageHeight is used to set the height of the image.
These method are invoked from the Show class at the keyReleased method to set the width and height of the image to display on the program window.
5 The drawIt method uses the Graphics2D class to display the image. The translate(x,y) method of the Graphics2D class moves the original coordinate (0,0) to the (x,y) coordinate or position.
We use the drawImage method to  display the image at the (x,y) position.
6 The setImageData has code to set the data of the image to be displayed. This method is invoked from the Show class to pass the image selected by the user to the ImageArea class so it is ready to draw on the drawing area.
7 The saveResizedImage method saves the resized image in a separated file. Before saving the file, an BufferedImage object bi is created then the current resized image is drawn this object so it is ready to save the file in the disk drive.
8 The Show class extends JFrame. It defines the program interface. In this program, the image is displayed by adding the ImageArea object ia at the center of the program window. We need two text boxes (txtWidth and txtHeight) to allow the user inputs or edits the width and height of the image. The OK button btOk invokes the saveResizedImage to save the resized image to the disk drive. The txtWidth, txtHeight, and btOK button are disabled (by invoking the activateControls method) when the program firstly opens.
9 The actionPeformed method has code to enable the btOK button and menu items to perform their tasks when the user clicks them. If the btOK button is clicked the saveResizedImage method is invoked to save the resized image to the disk drive. If the menu item Open is clicked the file chooser dialog box displays so the user can select the image file to display on the program window. The width and height of the image are displayed in the txtWidth and txtHeight text boxes.
The txtWidth, txtHeight, and btOK button are enabled (by invoking the activateControls method) if the valid image is selected to show on the program window. We don't allow the user to input or edit values in the text boxes or click the btOK button if there is no active image on the program window.
10 The activateControls method is implemented to enable or disable txtWidth, txtHeight, and btOK components. It accepts true or false value as its argument  The true value indicates that the components are enabled. Otherwise, the components are disabled.
11 The KeyList extends the KeyAdpater class to implement the keyTyped and keyReleased methods.
The keyTyped method defines code to hide key input if it is not a digit, backspace, or delete key. The
keyReleased method passes the width and height of the image to the ShowArea class so the image can be drawn on the ShowArea drawing object with this width and height when the user inputs or edits values in the width or height text boxes. When the size of the image changes, you need to invoke the repaint method of the ShowArea class, otherwise the image does not show.
12 The setImage method defines code to allow the user to choose the image file from the file chooser dialog.
When a valid image is selected, the width, height, and data of the image are sent to the ShowArea class by invoking the prepareImage method.
13 The prepareImage method defines code to send the width, height and data of the image the ShowArea class so it is ready to draw on the drawing area. This method is invoked when the user selects the image file from file chooser dialog.

No comments:

Post a Comment