返回顶部

收藏

Java判断图片格式的代码

更多
import java.io.File;  
import java.io.IOException;  
import java.util.Iterator;  
import javax.imageio.ImageIO;  
import javax.imageio.ImageReader;  
import javax.imageio.stream.ImageInputStream;  

public class ImageDemo {  

    /** 
     * @param args 
     */  
    public static void main(String[] args) {  

        File file = new File("E:/download_test/pics/1c/1cd5v0uya36wg0rf4fu39dtym.png");  

        boolean result = isImage(file);  
        System.out.println("result="+result);  

        getExtension(file);  
    }  

    public static void getExtension(File file) {  
        ImageInputStream iis = null;  
        try {  
            iis = ImageIO.createImageInputStream(file);  
            Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);   
            if(iter.hasNext()){  
                System.out.println("扩展名:"+iter.next().getFormatName());  
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }finally{  
            if(iis!=null){  
                try {  
                    iis.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  

    public static boolean isImage(File resFile){  
        ImageInputStream iis = null;  
        try {  
            iis = ImageIO.createImageInputStream(resFile);  
            Iterator<ImageReader> iter = ImageIO.getImageReaders(iis);   
            if (iter.hasNext()) {//文件不是图片   
                return true;  
            }   

        } catch (IOException e) {  
            e.printStackTrace();  
        }finally{  
            if(iis!=null){  
                try {  
                    iis.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
        return false;  
    }  

}  

标签:java

收藏

0人收藏

支持

0

反对

0

发表评论