imageio

Read image from file

In this tutorial we are going to see how to read an image from a file. This is very useful when you want to store image files in your system and you want to use them to enrich the graphics of your application.

In order to read image from a file:

  • You have to open a new File in the image file.
  • Use ImageIO.read(file) to get an Image object.

 
 
 
Let’s see the code snippet that follows:

package com.javacodegeeks.snippets.desktop;

import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ReadImageFromFile {

	public static void main(String[] args) throws IOException {

		// input image file
		File file = new File("myimage.jpg");
		Image image = ImageIO.read(file);

		int width = image.getWidth(null);
		int height = image.getHeight(null);

	}

}

 
This was an example on how to read image from a file.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Marial
Marial
5 years ago

I keep getting an exception. Does any prep work need to go into this? Such as having your image in a certain location or telling the code where the image is?

Back to top button