Java 이미지 타입 정보 얻기

2024. 12. 5. 19:12Java

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;

public class ImageTypeDetector {

    public static void main(String[] args) {
        String imagePath = "/path/to/your/image.jpg";

        try {
            File imageFile = new File(imagePath);
            String formatName = getImageFormat(imageFile);

            if (formatName != null) {
                System.out.println("Image format: " + formatName);
                if ("jpeg".equalsIgnoreCase(formatName)) {
                    System.out.println("This is a JPEG image.");
                } else if ("png".equalsIgnoreCase(formatName)) {
                    System.out.println("This is a PNG image.");
                } else {
                    System.out.println("Unknown image type.");
                }
            } else {
                System.out.println("Could not determine image type.");
            }
        } catch (IOException e) {
            System.out.println("Error reading the image: " + e.getMessage());
        }
    }

    public static String getImageFormat(File imageFile) throws IOException {
        try (ImageInputStream imageStream = ImageIO.createImageInputStream(imageFile)) {
            Iterator<ImageReader> readers = ImageIO.getImageReaders(imageStream);

            if (readers.hasNext()) {
                ImageReader reader = readers.next();
                return reader.getFormatName(); // Returns format like "jpeg" or "png"
            }
        }
        return null; // Return null if no readers are available
    }
}