Program to demonstrate how to read and write Image to a file in Java
Output of the program :
After reading Images from url and file system, ImageIO write method will create two image files with the name as : outUrl.jpg and url.jpg. There must be internet connection so that image at Url can be fetched successfully.
package com.hubberspot.example;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class ReadWriteImageDemo {
public static void main(String[] args) {
ReadWriteImageDemo demo = new ReadWriteImageDemo();
demo.imageProcessing();
}
public void imageProcessing(){
try {
// url of the image is wrapped in URL Object
URL url = new URL("http://1.bp.blogspot.com/-YUR1RgiOqW0/" +
"UC1UBYT7zZI/AAAAAAAAAeo/g34uyKSvTBI/s1600/Robot+keypress+event.jpg");
// BufferedImage ref variable holds the image read at specified URL
// by the ImageIO class through its static method read()
BufferedImage imageUrl = ImageIO.read(url);
// BufferedImage ref variable holds the image read at specified File
// by the ImageIO class through its static method read()
BufferedImage image = ImageIO.read(new File("out.gif"));
// ImageIO's class static method takes RenderedImage ,
// formatName, File and creates or transfer rendered image to
// File Object
ImageIO.write(imageUrl, "gif",new File("outUrl.gif"));
ImageIO.write(image, "gif",new File("url.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output of the program :
After reading Images from url and file system, ImageIO write method will create two image files with the name as : outUrl.jpg and url.jpg. There must be internet connection so that image at Url can be fetched successfully.