Java 이미지 타입 정보 얻기
2024. 12. 5. 19:12ㆍJava
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
}
}
'Java' 카테고리의 다른 글
STS 사용하지 않는 import 제거 단축키 (0) | 2024.12.27 |
---|---|
Java List<Map<String, Object> 분리 (0) | 2024.12.18 |
Java String[]에서 ""를 찾아내기 (0) | 2024.11.30 |
Java java.util.ConcurrentModificationException 처리 (1) | 2024.11.30 |
Java Exception에 변수 추가하기 (0) | 2024.11.30 |