LoginSignup
5

More than 5 years have passed since last update.

ImageIO経由で画像ファイルの拡張子を取得する

Posted at

ImageIOを経由して画像ファイルのフォーマットを取得します。

ImageUtil.java
/**
 * 指定した画像ファイルの内容から拡張子を取得する(対応フォーマット:jpg,bmp,png,gif)
 * @param target
 * @return
 * @throws IOException 
 */
public static String getImageFileExtensionByImageIO( File target ) throws IOException
{
    if( target == null || !target.exists() )
    {
        return "";
    }

    ImageInputStream iis = null;
    String ext = null;
    try
    {
        iis = ImageIO.createImageInputStream( target );
        Iterator<ImageReader> readers = ImageIO.getImageReaders( iis );
        if( !readers.hasNext() )
        {
            return "";
        }
        ImageReader reader = readers.next();
        String[] suffixes = reader.getOriginatingProvider().getFileSuffixes();
        if( suffixes == null || suffixes.length == 0 )
        {
            ext = suffixes[ 0 ];
        }
        else
        {
            ext = reader.getFormatName();
        }
    }
    finally
    {
        try
        {
            if( iis != null )
            {
                iis.close();
            }
        }
        catch( IOException e )
        {
        }
    }
    return ext;
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5