Sample Programs

Sample java program to read image

 package org.jusfortechies.example; 

 import java.awt.BorderLayout;
 import java.awt.Image;
 import java.io.BufferedInputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.URL;

 import javax.imageio.ImageIO;
 import javax.swing.ImageIcon;
 import javax.swing.JFrame;
 import javax.swing.JLabel;

 public class ReadImage {

   public static void main(String[] args) {

     String imagePath = "C:\\sample_image.gif";

     Image image = null;
     try {
       //To read image from a file
       File file = new File(imagePath);
       image = ImageIO.read(file);

       //To read image from an input stream
       InputStream is = new BufferedInputStream(new FileInputStream(
       imagePath));
       image = ImageIO.read(is);

       //To read from a URL
       URL url = new URL("http://www.jusfortechies.com/sample_image.gif");
       image = ImageIO.read(url);

     } catch (IOException e) {
       System.err.println("Error: " + e.getMessage());
     }
   }

 }


To test the image read, you can use below piece by inserting it towards the end of the above program

 
 JFrame frame = new JFrame();
 JLabel label = new JLabel(new ImageIcon(image));
 frame.getContentPane().add(label, BorderLayout.CENTER);
 frame.pack();
 frame.setVisible(true);



blog comments powered by Disqus