How to use the ImageIO class in Java?

In Java, we can utilize the ImageIO class to read and write image files. Here are some common usages of the ImageIO class:

  1. Read image file:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageReader {
    public static void main(String[] args) {
        try {
            File file = new File("path/to/image.jpg");
            BufferedImage image = ImageIO.read(file);
            // 处理图像
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. Save the image file:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageWriter {
    public static void main(String[] args) {
        try {
            BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
            // 处理图像
            File file = new File("path/to/save/image.jpg");
            ImageIO.write(image, "jpg", file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

When reading an image file, we use the ImageIO.read(file) method to read the file as a BufferedImage object. When writing an image file, we use the ImageIO.write(image, “format”, file) method, where image is the image object to be written, format is the image format (e.g. “jpg”, “png”, etc.), and file is the file path to save.

Please note that when using the ImageIO class, you need to handle the IOException exception. Additionally, you can use the ImageIO.getReaderFormatNames() and ImageIO.getWriterFormatNames() methods to retrieve a list of supported image format names.

bannerAds