2012-02-11 2 views

답변

2

이렇게하는 데 도움이되는 외부 도구가 있습니다. JMimeMagicJMagick을 확인하십시오. ImageIO 클래스를 사용하여 파일을 읽으려고 할 수도 있지만 비용이 많이 소요될 수 있으며 완전히 안전하지는 않습니다.

BufferedImage image = ImageIO.read(new FileInputStream(new File(..._))); 

이 질문은 몇 번 정도 질문되었습니다. 동일한 주제에 이러한 추가 스레드를 참조하십시오

Check if a file is an image

How to check a uploaded file whether it is a image or other file?

+0

시도 이미지가 확인됩니다. 이것은 쉽게 발생할 수 있습니다 ** OutOfMemoryError ** –

+0

이것은 여러 파일의 경우에는 좋은 접근 방법이 아닙니다. –

11
public static boolean isImage(File file) { 
    if (file == null || !file.exists()) { 
     return false; 
    } 
    BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(file.getPath(), options); 
    return options.outWidth != -1 && options.outHeight != -1; 
} 
+0

어떻게 작동하는지 설명해 주시겠습니까? – Micro

+0

@MicroR,'options.inJustDecodeBounds = true;를 설정하면'BitmapFactory'가 전체 이미지의 데이터를 디코딩하지 않고 이미지의 메타 데이터 만 디코딩합니다. file이'BitmapFactory'보다 유효한 이미지라면 메타 데이터를 파싱하고'options.outWidth'와'options.outHeight'를 채 웁니다. 이 필드에는 이미지의 폭과 높이가 포함됩니다. 디코딩 오류가 발생하면 필드에 -1이 포함됩니다. docs http://developer.android.com/intl/ru/reference/android/graphics/BitmapFactory.Options.html#outWidth를 참조하십시오. – danik

0

메모리와 많은면에서 * 이것은이 코드 세그먼트를 아주 아주 나쁜 *을

public static boolean isViewableImage(String name) { 
    String suffix = name.substring(name.lastIndexOf('.') + 1).toLowerCase(); 
    if (suffix.length() == 0) 
     return false; 
    if (suffix.equals("svg")) 
     // don't support svg preview 
     return false; 

    String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(suffix); 
    if (mime == null) 
     return false; 
    return mime.contains("image"); 
} 
관련 문제