- Reading/Loading an Image
- How to read an image from file or URL
- 1. Read from local file
- 2. Read from URL
- ImageIO Example
- How to read and write image file in Java
- Creating class
- The main() method
- Variables
- Reading Image
- Writing Image
- Final code
- Another way to write the above code
- How to read and write images in Java
- How to read and write images in Java
- How to read an image in Java with ImageIO
- How to read an image in Java with JDeli
- How to write out an image in ImageIO
- How to write out an image with JDeli
- Download your JDeli guide:
- Start reading and writing images with one line of code
Reading/Loading an Image
When you think of digital images, you probably think of sampled image formats such as the JPEG image format used in digital photography, or GIF images commonly used on web pages. All programs that can use these images must first convert them from that external format into an internal format.
Java 2D supports loading these external image formats into its BufferedImage format using its Image I/O API which is in the javax.imageio package. Image I/O has built-in support for GIF, PNG, JPEG, BMP, and WBMP. Image I/O is also extensible so that developers or administrators can «plug-in» support for additional formats. For example, plug-ins for TIFF and JPEG 2000 are separately available.
To load an image from a specific file use the following code, which is from LoadImageApp.java :
BufferedImage img = null; try < img = ImageIO.read(new File("strawberry.jpg")); >catch (IOException e)
Image I/O recognises the contents of the file as a JPEG format image, and decodes it into a BufferedImage which can be directly used by Java 2D.
LoadImageApp.java shows how to display this image.
If the code is running in an applet, then its just as easy to obtain the image from the applet codebase. The following excerpt is from LoadImageApplet.java :
The getCodeBase method used in this example returns the URL of the directory containing this applet when the applet is deployed on a web server. If the applet is deployed locally, getCodeBase returns null and the applet will not run.
The following example shows how to use the getCodeBase method to load the strawberry.jpg file.
Note: If you don’t see the applet running, you need to install at least the Java SE Development Kit (JDK) 7 release.
LoadImageApplet.java contains the complete code for this example and this applet requires the strawberry.jpg image file.
In addition to reading from files or URLS, Image I/O can read from other sources, such as an InputStream. ImageIO.read() is the most straightforward convenience API for most applications, but the javax.imageio.ImageIO class provides many more static methods for more advanced usages of the Image I/O API. The collection of methods on this class represent just a subset of the rich set of APIs for discovering information about the images and for controlling the image decoding (reading) process.
We will explore some of the other capabilities of Image I/O later in the Writing/Saving an Image section.
How to read an image from file or URL
The “javax.imageio” package is used to deal with the Java image stuff. Here’s two “ImageIO” code snippet to read an image file.
1. Read from local file
File sourceimage = new File("c:\\mypic.jpg"); Image image = ImageIO.read(sourceimage);
2. Read from URL
URL url = new URL("http://www.mkyong.com/image/mypic.jpg"); Image image = ImageIO.read(url);
ImageIO Example
In this example, you will use ImageIO to read a file from an URL and display it in a frame.
package com.mkyong.image; import java.awt.Image; import java.io.IOException; 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 ) < Image image = null; try < URL url = new URL("http://www.mkyong.com/image/mypic.jpg"); image = ImageIO.read(url); >catch (IOException e) < e.printStackTrace(); >JFrame frame = new JFrame(); frame.setSize(300, 300); JLabel label = new JLabel(new ImageIcon(image)); frame.add(label); frame.setVisible(true); > >
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.
How to read and write image file in Java
In this project we will learn to read and write image file using Java programming language.
Open a new file and name it MyImage.java
It is important that you save the source code file in .java format.
To read and write image file we have to import the File class. For this we will write:
When we perform read/write operations, also known as I/O or Input/Output operation, errors may occur. So, to handle errors we use the IOException class. For this we write:
To hold the image we create the BufferedImage object. For this we import the BufferedImage class.
import java.awt.image.BufferedImage;
To perform the image read write operation we will import the ImageIO class. For this we will write:
import javax.imageio.ImageIO;
Creating class
Now we will create our MyImage class. For this we will write:
Note! Since our file name is MyImage.java so, our class must have the name MyImage.
The main() method
Now, inside this class we will define the main() function and since we are going to perform IO operation so, we will add the throws IOException right next to the main() function.
So, our code will now look like the following:
public class MyImage
public static void main(String args[])throws IOException
>
>
Variables
The image we are going to read has a width 963px and height 640px. So, we will declare two variables inside the main() function to hold the dimension of the image.
int width = 963; //width of the image
int height = 640; //height of the image
Next we create a BufferedImage variable image and File variable f and set both of them to null.
BufferedImage image = null;
File f = null;
Now, our code will look something like this:
public class MyImage
public static void main(String args[])throws IOException int width = 963; //width of the image
int height = 640; //height of the image
BufferedImage image = null;
File f = null;
>
>
Reading Image
Now we will read the image file.
Please note, while performing read/write operation it is always suggested to use the try-catch block. This is because IO operation can generate exception (error) and to take care of that IO exception we need a exception handling code. If we don't use the try-catch block then our code will simply crash when an exception (error) will occur.
try // some code goes here.
>catch(IOException e) // some code goes here.
>
Inside the try body we will create an object of File class and pass as parameter the image file path.
f = new File("D:\\Image\\Taj.jpg"); //image file path
Note! The image file we are using in the above line is named as Taj.jpg and it is in Image folder which is inside the D: drive on a Windows PC.
Next, we will create an object of BufferedImage type and pass as parameter the width, height and image int type.
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Note! TYPE_INT_ARGB means that we are representing the Alpha, Red, Green and Blue component of the image pixel using 8 bit integer value.
Next, we will read the image using the function read() of the ImageIO class and pass as parameter the image file path which we have stored in variable f.
Then we will output "Reading Complete"
System.out.println("Reading complete.");
Inside the catch body we will output the error message. For this we will write:
Now, our code will look something like this:
public class MyImage
public static void main(String args[])throws IOException int width = 963; //width of the image
int height = 640; //height of the image
BufferedImage image = null;
File f = null;
//read image
try f = new File("D:\\Image\\Taj.jpg"); //image file path
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
image = ImageIO.read(f);
System.out.println("Reading complete.");
>catch(IOException e) System.out.println("Error: "+e);
>
>
>
Writing Image
Similarly, to write the image as a file we will again use the try-catch block. We will first create an object of File type and pass as parameter the image file path where we want to write (save) the image. For this we will write:
f = new File("D:\\Image\\Output.jpg"); //output file path
Next, we will write the image using the write() function of the ImageIO class. For this we will write:
Note! image is the variable that stores the image that we want to write (save). "jpg" is the destination file extension. And f is the variable that stores the destination file path name.
Then we will output "Writing Complete"
System.out.println("Writing complete.");
Inside the catch body we will output the error message. For this we will write:
Final code
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class MyImage
public static void main(String args[])throws IOException int width = 963; //width of the image
int height = 640; //height of the image
BufferedImage image = null;
File f = null;
//read image
try f = new File("D:\\Image\\Taj.jpg"); //image file path
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
image = ImageIO.read(f);
System.out.println("Reading complete.");
>catch(IOException e) System.out.println("Error: "+e);
>
//write image
try f = new File("D:\\Image\\Output.jpg"); //output file path
ImageIO.write(image, "jpg", f);
System.out.println("Writing complete.");
>catch(IOException e) System.out.println("Error: "+e);
>
>//main() ends here
>//class ends here
Another way to write the above code
/**
* File: ReadWriteImage.java
*
* Description:
* Read and write image.
* @author Yusuf Shakeel
* Date: 26-01-2014 sun
*
* www.github.com/yusufshakeel/Java-Image-Processing-Project
*/
import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class MyImage
public static void main(String args[])throws IOException
BufferedImage image = null;
File f = null;
//read image file
try
f = new File("D:\\Image\\Taj.jpg");
image = ImageIO.read(f);
>catch(IOException e)
System.out.println("Error: "+e);
>
//write image
try
f = new File("D:\\Image\\Output.jpg");
ImageIO.write(image, "jpg", f);
>catch(IOException e)
System.out.println("Error: "+e);
>
>//main() ends here
>//class ends here
You can use any of the two codes to read and write image file in Java.
How to read and write images in Java
In this post, I will show you how to read and write image files in Java. I will demonstrate 2 different ways of doing this. The first is with the ImageIO, and the second is with our JDeli image library.
If you are just looking for an Image Viewer, JDeli includes a built-in Image Viewer.
How to read and write images in Java
Java provides a single type of object called a BufferedImage for images in Java.
A BufferedImage can be read from lots of different image types (ie BMP, HEIC, etc). Not all of these are supported by ImageIO itself but there are plugins to extend ImageIO, and other libraries such as Apache Imaging and JDeli.
In Java itself all the complexity of different image types is hidden – you work on a BufferedImage. Java allows direct access to the image pixels and colour information as well as allowing transformations and image processing.
Here is a list of how to read and write common Image file formats in Java.
How to read an image in Java with ImageIO
Step 1 Create a File handle, InputStream or URL pointing to the raw image.
Step 2 ImageIO will now be able to read an image file into a BufferedImage. This syntax is like so:
BufferedImage image = ImageIO.read(fileOrInputStreamOrURL)
How to read an image in Java with JDeli
Step 1 Add JDeli to your class or module path. (download the trial jar).
Step 2 Create a File, InputStream pointing to the raw image. You can also use a byte[] containing the image data.
Step 3 Read the image into a BufferedImage
BufferedImage image = JDeli.read(file);
How to write out an image in ImageIO
This example shows the exact settings for a PNG image.
Step 1 Create a File (or OutputStream) object
File file = new File("/path/to/outputFile.png"));
Step 2 Pass image, PNG type and File (or OutputStream) object into write method
ImageIO.write(bufferedImage, "PNG", file);
How to write out an image with JDeli
This example shows the exact settings for a PNG image.
Step 1 Add JDeli to your class or module path. (download link to the trial jar).
Step 2 Create a File (or OutputStream) object
File file = new File("/path/to/outputFile.png"));
Step 3 Pass image, PNG type and File (or OutputStream) object into write method
JDeli.write(bufferedImage, "PNG", file);
In JDeli you can also use a typesafe version
JDeli.write(bufferedImage, OutputFormat.PNG, file);
or pass in a PngEncoderOptions object for more control over image output.
PngEncoderOptions options = new PngEncoderOptions(); JDeli.write(bufferedImage, options, file);
Download your JDeli guide:
Start reading and writing images with one line of code
Read: BufferedImage image = JDeli.read(streamOrFile);
Write: JDeli.write(myBufferedImage, OutputFormat.HEIC, outputStreamOrFile)
Bethan Palmer Bethan is a Java developer and a Java Champion. She has spoken at conferences including JavaOne/Code One, DevFest and NetBeans days. She has a degree in English Literature.