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)
上一篇 2025年9月14日 上午11:15
下一篇 2025年9月14日 上午11:43


相关推荐

  • 先验概率和后验概率的定义是什么_先验和后验什么意思

    先验概率和后验概率的定义是什么_先验和后验什么意思话不多说,我因为在学习朴素贝叶斯的时候有点分不清楚先验概率、后验概率,所以就网上找了一些资料,大家各有各的理解,但感觉还是不太能从定义上区分,所以就有了下面这张图:图里面说的还是比较清晰的,大家有不理解的地方可以沟通交流嘛。…

    2022年10月18日
    7
  • 1.numpy中三维数组的理解

    1.numpy中三维数组的理解numpy 中三维数组的理解三维数组图形立方体图片中的三维数组 RNN 中序列数据的三维数组迭代数据中的三维数组三维数组图形 立方体我们在做图像处理 RNN 序列数据 迭代数据的时候会遇到三维数组 我们应该理解这三种情况下三维数组的数据分布是怎么样的 才能更好的理解算法 和程序的原理 其实三维数组就是三维的数 这么说确实很抽象 空洞 但是我们可以将三维数组想象成为一个立方体 三维数组的每个维度代表

    2026年3月19日
    2
  • 用python画出爱心_Python编出爱心

    用python画出爱心_Python编出爱心Python中可以使用turtle库来画图,通过控制画笔运动来实现在画布上画图案。使用Python画爱心代码如下:#!/usr/bin/envpython#-*-coding:utf-8-*-importturtleimporttime#画心形圆弧defhart_arc():foriinrange(200):turtle.right(1)turtle.forward(2)de…

    2025年9月26日
    8
  • Windows 结合最新版 ComfyUI 部署图像大模型详细步骤(含Web和本地)

    Windows 结合最新版 ComfyUI 部署图像大模型详细步骤(含Web和本地)

    2026年3月16日
    2
  • WPF中的StackPanel、WrapPanel、DockPanel

    WPF中的StackPanel、WrapPanel、DockPanel一、StackPanelStackPanel是以堆叠的方式显示其中的控件1、可以使用Orientation属性更改堆叠的顺序Orientation=”Vertical”默认,由上到下显示各控件。控件在未定义的前提下,宽度为StackPanel的宽度,高度自动适应控件中内容的高度1:2:ButtonA3:ButtonB4:B

    2022年7月22日
    14
  • SpringBoot 出现 Content type ‘application/x-www-form-urlencoded;charset=UTF-8’ not supported

    SpringBoot 出现 Content type ‘application/x-www-form-urlencoded;charset=UTF-8’ not supported问题点1:如果Content-Type设置为“application/x-www-form-urlencoded;charset=UTF-8”无论是POST请求还是GET请求都是可以通过这种方式成功获取参数,但是如果前端POST请求中的body是Json对象的话,会报上述错误。请求中传JSON时设置的Content-Type如果是application/json或者text/json时,…

    2022年7月27日
    75

发表回复

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

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