检测给定文件是否为图像,并且是java中特定类型的有效图像 [英] Detect if given file is image and is valid image of specific type in java

查看:190
本文介绍了检测给定文件是否为图像,并且是java中特定类型的有效图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求从用户输入文件获取,该文件应该只是指定类型的图像。例如。只有 JPEG s。必须拒绝其他文件。

I have requirement to get from user input file which should be image only of specified type. E.g. only JPEGs. Other files must be rejected.

所以我对文件实施了天真的基本检查

So I implemented naive basic check for file

fileName.toLowerCase().endsWith(".jpg") || fileName.toLowerCase().endsWith(".jpeg")

所以如果用户上传了file.png,这个文件被拒绝了。但随后用户意识到,如果他们只是将file.png重命名为file.jpg,那么该文件将被上传。

So if user uploaded file.png, this file was rejected. But then users realized, that if they simply rename file.png to file.jpg, the file will be uploaded.

是否可以检测提供的文件是否为有效图像给定类型只使用 JAVA SDK 没有外部罐子? (注意我还在使用JDK6)。谢谢。

Is there way to detect if supplied file is valid image of given type using only JAVA SDK without external jars? (note I'm still working with JDK6). Thanks.

推荐答案

进行一些天真的检查以将JPEG与PNG分开应该相对容易。根据维基百科,JPEG文件始终以 FF D8开头。然而,PNG似乎从 89 50 开始,因此人们可以轻松区分这两者只是从文件中读取一两个字节。

It should be relatively easy to do some naive checking to separate a JPEG from a PNG. According to Wikipedia, JPEG files always start with FF D8. PNGs however seem to start with 89 50, so one can easily distinguish between the two from just reading a byte or two from the file.

我建议查找最重要图像类型的文件格式,以确保没有其他主流版本以 FF D8 开头。但似乎不太可能。

I would recommend looking up the file formats of the most important image types just to make sure there isn't some other mainstream one starting with FF D8. It seems unlikely however.

编辑:JPEG,PNG,GIF,BMP和TIFF似乎都在文件的开头都有魔术值,告诉他们与其他类型分开。

JPEG, PNG, GIF, BMP and TIFF all seem to have magic values at the start of the files to tell them apart form other types.

这篇关于检测给定文件是否为图像,并且是java中特定类型的有效图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆