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


相关推荐

  • python的源代码下载_官方下载python源码,编译linux版本的python「建议收藏」

    python的源代码下载_官方下载python源码,编译linux版本的python「建议收藏」我这里使用的时centos7-mini,centos系统本身默认安装有python2.x,版本x根据不同版本系统有所不同,可通过python–V或python–version查看系统自带的python版本有一些系统命令时需要用到python2,不能卸载1、安装依赖包1)首先安装gcc编译器,gcc有些系统版本已经默认安装,通过gcc–version查看,没安装的先安装g…

    2022年8月23日
    15
  • OpenClaw 云端部署 vs 本地部署:5 大维度完全对比指南

    OpenClaw 云端部署 vs 本地部署:5 大维度完全对比指南

    2026年3月13日
    1
  • 打印机显示smtp服务器未设置,打印机smtp服务器设置

    打印机显示smtp服务器未设置,打印机smtp服务器设置打印机smtp服务器设置内容精选换一换安装完模型小型化工具,量化模型前,用户需要获取并安装Caffe源代码增强包caffe_patch.tar.gz,在Caffe源码中增加部分源码文件、动态库文件及修改部分源代码。安装过程整体分为两部分:拷贝新增源码和动态库文件到Caffe环境caffe-master工程目录下。对Caffe环境caffe-master工程目录下部分文件安装p本文档所述Demo在…

    2022年10月20日
    6
  • linux常用命令csdn_linux的rename命令

    linux常用命令csdn_linux的rename命令一.基础知识1.1liunx系统的文件结构/dev设备文件/etc大多数配置文件/home普通用户的家目录/lib32位函数库/lib6464位库/media手动临时挂载点/mnt手动临时挂载点/opt第三方软件安装位置/proc进程信息及硬件信息/root临时设备的默认挂载点/sbin系统管理命令/srv

    2025年11月10日
    8
  • 超声波雷达应用总结「建议收藏」

    超声波雷达应用总结「建议收藏」超声波雷达应用总结超声波雷达简介超声波雷达的数学模型超声波雷达的特性超声波雷达配置情况无人驾驶中超声波主要的应用超声波雷达简介常见的超声波雷达有两种。第一种是安装在汽车前后保险杠上的,也就是用于测量汽车前后障碍物的倒车雷达,这种雷达业内称为UPA;第二种是安装在汽车侧面的,用于测量侧方障碍物距离的超声波雷达,业内称为APA。UPA超声波雷达UPA超声波雷达的探测距离一般在15~250cm之间,主要用于测量汽车前后方的障碍物。如下图所示,为单个UPA的探测范围示意图。APA超声波雷达A

    2025年10月30日
    5
  • 手机gif录屏软件_手机录制gif软件

    手机gif录屏软件_手机录制gif软件gif录屏手机app是一款免费专业的视频剪辑制作软件,下载gif录屏apk支持GIF动画录屏以及MP4视频录屏,通过手机录屏GIF制作软件,一键轻松进行视频编辑、视频压缩和视频拼接。软件介绍gif录屏app是一款完全免费的专业高清流畅的录屏软件,支持GIF动画录屏以及MP4视频录屏。功能强大,操作简单,用户可以轻松录屏,录屏生成GIF回味用户自动生成GIF文件;将屏幕录制到动画文件.GIF,一边录…

    2026年2月2日
    4

发表回复

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

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