8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

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;
}
8
5
0

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
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?