2012-12-07 6 views
15

可能性の重複:
Know if a file is a image in Java/AndroidAndroid:ファイルがイメージかどうかを確認するには?

それが画像であればどのように私は、ファイルを確認することができますか?

を(file.isImage)場合....

を、それは私がMagickImage libにでそれを行うことができますどのように、標準ライブラリにはできません場合は、次のような ?

ありがとうございます!

+2

は、ファイルの拡張子を確認することができかもしれ.. –

+1

可能性のある重複http://stackoverflow.com/q/9244710/681807 –

+0

私はそれはないと思いますファイル拡張子でチェックする正しい方法。なぜなら、bmp、jpg、jpeg、png、gif、tifなどのあらゆる画像ファイル拡張子をチェックする関数を作成しなければならないからです... –

答えて

16

このコードをお試しください。

public class ImageFileFilter implements FileFilter 
    { 
     File file; 
     private final String[] okFileExtensions = new String[] {"jpg", "png", "gif","jpeg"}; 

     /** 
     * 
     */ 
     public ImageFileFilter(File newfile) 
     { 
      this.file=newfile; 
     } 

     public boolean accept(File file) 
     { 
      for (String extension : okFileExtensions) 
       { 
        if (file.getName().toLowerCase().endsWith(extension)) 
        {    
        return true; 
        } 
       } 
      return false;   
     } 

    } 

「うまくいくよ。

このように使用 (新しいImageFileFilter(パスファイル名));

+4

これはうまくいきました...今はすべての画像拡張子を検索する必要があります... –

+0

Most歓迎親愛なる。 –

+9

@ ZalaJanaksinhこれは、「画像ファイル拡張子」を持つ任意のファイルに対して 'true'を返します。 'test.mp3'の名前を' test.jpg'に変更すると、メソッドは 'true'を返します。 – Baz

40

ファイルがイメージかどうかを確認したい場合は、それを読む必要があります。画像ファイルはファイル拡張規則に従わない場合があります。あなたは、次のようBitmapFactoryでファイルを解析しようとすることができます:

BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inJustDecodeBounds = true; 
Bitmap bitmap = BitmapFactory.decodeFile(path, options); 
if (options.outWidth != -1 && options.outHeight != -1) { 
    // This is an image file. 
} 
else { 
    // This is not an image file. 
} 
+1

しかし、 'try'' catch'が必要でしょうか? – Doomsknight

+0

BitmapFactory.decodeFile(path、options)の戻り値をチェックすることができます。 – zsxwing

+3

options.inJustDecodeBounds = true decodeFileは画像の幅と高さのみを解析するため、解析時間のコストを削減します。 – zsxwing

関連する問題