在一些java需要上传的需求中,大家都需要验证上传文件的类型,那么上传图片时, 大家肯定会验证扩展名,但是如果用户把一个别的文件的扩展名改成jpg或者gif这样上传就不好判断了,所以大家可以用下面的方法进行判断
public static boolean isImage(byte[] imageContent) {
        if (imageContent == null || imageContent.length == 0) {
            return false;
        }
        Image img = null;
        InputStream is = null;
        try {
            is = new ByteArrayInputStream(imageContent);
            img = ImageIO.read(is);
            if (img == null || img.getWidth(null) <= 0
                    || img.getHeight(null) <= 0) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                }
            }
        }
    }
	
posted on 2010-09-26 10:41 
青菜猫(孙宇) 阅读(3006) 
评论(2)  编辑  收藏  所属分类: 
java