java判断文件是否为图片格式_java读取图片流

java判断文件是否为图片格式_java读取图片流前言Java检查文件类型有几种方法:1.判断文件后缀名Stringextension="";inti=fileName.lastIndexOf(‘.’);if(i>0){extension=fileName.substring(i+1);}//…if("jpg".equal

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

前言

在上传图片文件的时候除了需要限制文件的大小,通常还需要对文件类型进行判断。因为用户可能会上传任何东西上来,如果被有心人上传木马到你服务器那就麻烦了。

Java检查文件类型的方法

判断文件后缀名

String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0) {
    extension = fileName.substring(i+1);
}
//...
if("jpg".equals(extension)){
	//your code
}

但是这种方法不太靠谱

判断文件头

在后缀未知,或者后缀被修改的文件,依然通过文件头来判断该文件究竟是什么文件类型。我们可以使用一个文本编辑工具如UltraEdit打开文件(16进制模式下),然后看文件头是什么字符,以下是常见图片类型的文件头字符(16进制)

JPEG (jpg),文件头:FFD8FF 
PNG (png),文件头:89504E47 
GIF (gif),文件头:47494638 
TIFF (tif),文件头:49492A00 
Windows Bitmap (bmp),文件头:424D

通过MimetypesFileTypeMap来判断


public class ImageCheck {
	private  MimetypesFileTypeMap mtftp;
	
	public ImageCheck(){
		mtftp = new MimetypesFileTypeMap();
		/* 不添加下面的类型会造成误判 详见:http://stackoverflow.com/questions/4855627/java-mimetypesfiletypemap-always-returning-application-octet-stream-on-android-e*/
		mtftp.addMimeTypes("image png tif jpg jpeg bmp");
	}
	public  boolean isImage(File file){
		String mimetype= mtftp.getContentType(file);
		String type = mimetype.split("/")[0];
	    return type.equals("image");
	}
	
}

该方法貌似是基于文件后缀进行判断的,修改文本文件后缀为jpg,也会返回true。

通过ImageIO来判断

try {
	// 通过ImageReader来解码这个file并返回一个BufferedImage对象
	// 如果找不到合适的ImageReader则会返回null,我们可以认为这不是图片文件
	// 或者在解析过程中报错,也返回false
    Image image = ImageIO.read(file);
    return image != null;
} catch(IOException ex) {
    return false;
}

注意: 该方法适用的图片格式为 bmp/gif/jpg/png

测试

测试不同的方法

public class ImageCheckerTest {
    private File imageFile;//真正的图片文件            图片
    private File txt2ImageFile; //将txt后缀改为jpg    txt
    private File image2txt;//将图片文件后缀改为txt      图片
    @Before
    public void init(){
        imageFile = new File("D:\\image.jpg");
        txt2ImageFile = new File("D:\\txt.jpg");
        image2txt = new File("D:\\image.txt");
    }


    @Test
    public  void test1(){
        MimetypesFileTypeMap mtftp = new MimetypesFileTypeMap();
        mtftp.addMimeTypes("image png tif jpg jpeg bmp");

        String mimetype = mtftp.getContentType(imageFile);
        String type = mimetype.split("/")[0];
        assertTrue(type.equals("image"));


        mimetype = mtftp.getContentType(txt2ImageFile);
        type = mimetype.split("/")[0];
        assertFalse(type.equals("image"));

        mimetype = mtftp.getContentType(image2txt);
        type = mimetype.split("/")[0];
        assertTrue(type.equals("image"));
    }

    @Test
    public void test2() throws IOException {
        String mimetype = Files.probeContentType(imageFile.toPath());
        String type = mimetype.split("/")[0];
        assertTrue(type.equals("image"));

        mimetype = Files.probeContentType(txt2ImageFile.toPath());
        type = mimetype.split("/")[0];
        assertFalse(type.equals("image"));

        mimetype = Files.probeContentType(image2txt.toPath());
        type = mimetype.split("/")[0];
        assertTrue(type.equals("image"));
    }

    @Test
    public void test3() {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String type = fileNameMap.getContentTypeFor(imageFile.getAbsolutePath()).split("/")[0];
        assertTrue(type.equals("image"));

        type = fileNameMap.getContentTypeFor(txt2ImageFile.getAbsolutePath()).split("/")[0];
        assertFalse(type.equals("image"));

        type = fileNameMap.getContentTypeFor(image2txt.getAbsolutePath()).split("/")[0];
        assertTrue(type.equals("image"));
    }

    @Test
    public void test4() throws IOException {
        assertTrue(check4(imageFile));
        assertFalse(check4(txt2ImageFile));
        assertTrue(check4(image2txt));
    }

    public boolean check4(File file){
        try {
            Image image = ImageIO.read(file);
            return image != null;
        } catch(IOException ex) {
            return false;
        }
    }





}

我准备了3个文件,第1个是真正的图片文件,第2个是后缀为jpg的文本文件,第3个为后缀是txt的图片文件

测试结果如下:

这里写图片描述

只有第4个测试用例成功的。其他的都死在对第2个文件的判断上了,我把对第2个文件的判断代码都删掉,结果又死在对第3个文件的判断上了。

测试不同的图片格式

接下来测试方法4能适用的图片格式:

这里写图片描述

通过图片转换器将jpg图片转换为下面的格式:

这里写图片描述

public class ImageCheckerTest {
    private File path;
    @Before
    public void init(){
        path = new File("D:\\images");
    }

    public boolean check4(File file){
        try {
            Image image = ImageIO.read(file);
            return image != null;
        } catch(IOException ex) {
            return false;
        }
    }

    @Test
    public void testImageType() {
        File[] files = path.listFiles();
        for (File file : files){
            System.out.println("Check file:     " + file.getName() +" : " + check4(file));
        }

    }
}

结果如下:

Check file:     image.bmp : true
Check file:     image.dcx : false
Check file:     image.gif : true
Check file:     image.ico : false
Check file:     image.j2k : false
Check file:     image.jp2 : false
Check file:     image.jpg : true
Check file:     image.pcx : false
Check file:     image.png : true
Check file:     image.psd : false
Check file:     image.tga : false
Check file:     image.tif : false

该方法适用的图片格式为:bmp/gif/jpg/png

总结

如果对安全性和图片格式完整性要求高的话建议使用第三方jar包。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/197085.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 到底什么是hash呢?hash碰撞?为什么HashMap的初始容量是16?

    到底什么是hash呢?hash碰撞?为什么HashMap的初始容量是16?一,到底什么是hash呢?作者:知乎用户链接:https://www.zhihu.com/question/26762707/answer/40119521来源:知乎著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。hash(散列、杂凑)函数,是将任意长度的数据映射到有限长度的域上。直观解释起来,就是对一串数据m进行杂糅,输出另一段固定长度的数据h,作为这段数据的…

    2022年6月16日
    38
  • linux修改用户名密码的命令_centos修改用户密码命令

    linux修改用户名密码的命令_centos修改用户密码命令修改Linux用户名密码的指令,在更改成需要修改密码的用户名sudopasswd<用户名>随后输入两次新密码即可欢迎小伙伴讨论,文章内容如有错误请在评论区评论或发私聊消息,谢谢你。

    2022年9月2日
    2
  • s一般怎么称呼自己的m_英文信的开头和结尾,怎么写才不会出错?

    s一般怎么称呼自己的m_英文信的开头和结尾,怎么写才不会出错?一提起写英文信,很多人觉得很简单,不就是开头叫声dear,结尾说句sincerely吗?但其实,根据不同的情况,前后都会有特殊的要求。我们要怎么写才不会出错呢?首先,说一种我们最熟悉的情况,就是当你明确知道对方姓名的时候,我们应该如何写开头和结尾。正式的写法就是dear后面加上具体称呼,比如马丁先生“Mr.Martin”,这时候应该写他的姓氏(surname)。Mr.即Mister的缩写,意思是…

    2022年6月23日
    115
  • main方法的各种书写样式

    main方法的各种书写样式以下是一些正确的和一个错误的:publicstaticvoidmain(String[]args)publicstaticfinalvoidmain(String[]args)staticpublicvoidmain(String[]args)staticpublicsynchronizedvoidmain(String[]args)staticpublicabstractvoidmain(String[]args)//错误,abstract要求没

    2022年5月31日
    36
  • batchnorm原理理解「建议收藏」

    batchnorm原理理解「建议收藏」接触CNN也一段时间了,最近也到了秋招期间,面试的时候可能会问到的一些内容需要做一个整理CNN-BN层参考了一个大神的博客,感觉讲的很深入也很好理解。我这里主要是对他的博客做一个自己的归纳整理,主要是为了方便自己去理解,也欢迎大家一起讨论自己的理解。这里给出大神的博客地址:https://blog.csdn.net/qq_25737169/article/details/79048…

    2022年5月16日
    42
  • Mysql : tinytext, text, mediumtext, longtext[通俗易懂]

    Mysql : tinytext, text, mediumtext, longtext[通俗易懂]Mysql:tinytext,text,mediumtext,longtext(2012-08-0114:26:23)转载▼标签:杂谈 分类:mysql一、数字类型类型 范围 说明 Char(N)[binary] N=1~255个字元binary:分辨大小写 固定长度 std_namecahr(32)…

    2022年8月13日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号