728x90 AdSpace

Trending

Handling Images in a Java GUI Application




The basic operations with images:-

  • Reading an image.
  • Displaying an Image.
  • Drawing to an image.
  • Saving an image.
Reading an Image
use below code to read an image file from hard disk.
     try {

       java.io.BufferedReader   img = javax.ImageIO.read(new File("xo.jpg"));
       } catch (IOException e) {
        System.out.println("image not found");
     }
Displaying an image:
    public void paint(Graphics g) {
        g.drawImage(img, 0, 0, null);
    }
                                  

Below code displays image on JFrame:-

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.swing.*;
class LoadImageApp extends Component {
BufferedImage img;
public void paint(Graphics g) {//drawing an image file
g.drawImage(img, 0, 0, null);
}
public LoadImageApp() {
try {//loading an image file
img = ImageIO.read(new File("1.jpg"));
} catch (Exception e) {
}
}
public static void main(String[] args) {
JFrame f = new JFrame("Load Image Sample");
f.add(new LoadImageApp());
f.setVisible(true);
}
}





























Drawing to an image:
 use below method to display specific part of an image:
            void Graphics2D.drawImage(img,destx1,desty1,destx2,desty2,srcx1,srcy1,srcx2,srcy2,ImageObserverl);
 dest:destination coordinates src:source destination 
public void paint(Graphics g) {//drawing an image file
g.drawImage(img,0,0,30,30,0,0,30,30,null);}

 above method can also be used to zoom the image  by incrementing destination file.
 Saving an Image:
 method to save an image into a file.
static boolean ImageIO.write(img,format,file);
 try{
File outputfile=new File("newimg.png");
ImageIO.write(img,"png",outputfile);
}


stay Connected......!

Handling Images in a Java GUI Application Reviewed by Unknown on 10:26 Rating: 5 The basic operations with images:- Reading an image. Displaying an Image. Drawing to an image. Saving an image. Reading an Im...

No comments: