Read an Image from File or URL or Class Path
In the following tutorial we demonstrate how to read an image from a File
, URL
, class-path
or InputStream
.
How to Read an Image in Java
This example shows how to read an image in java.
File
– specifies a local folder on your computer/server.URL
– specifies a resource from the internet.class-path
– specifies a class path resource located insrc/main/resources
.InputStream
– specifies aInputStream
.
package com.memorynotfound.image;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class ReadImageExample {
public static void main(String... args) throws IOException {
// read image from folder
File folderInput = new File("/tmp/duke.png");
BufferedImage folderImage = ImageIO.read(folderInput);
// read image from url
URL urlInput = new URL("https://memorynotfound.com/wp-content/uploads/java-duke.png");
BufferedImage urlImage = ImageIO.read(urlInput);
// read image from class-path
File classPathInput = new File(ReadImageExample.class.getResource("duke.png").getFile());
BufferedImage classpathImage = ImageIO.read(classPathInput);
// read image from inputstream
InputStream isInput = new FileInputStream("/tmp/duke.png");
BufferedImage inputStreamImage = ImageIO.read(isInput);
}
}
There is no BufferedImage ImageIO in the JDK of 11. What alternatives do I have then?