gpt4 book ai didi

java - 如何在java中验证图像标题

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:09:59 27 4
gpt4 key购买 nike

我有一个可用于上传文件的网页。现在我需要检查图像文件类型是否正确,如 png、jpg、jpeg、gif

我正在使用请求附带的 mimeType,但是如果我正在加载重命名为 .jpg 文件的 .txt 文件,那么 mime 类型也显示图像/jpg,基本上我不想上传这个文件.现在我想确保没有人能够上传在 .jpg/.png 中重命名的 .txt 文件....

为了引用,我在这里放了一段代码:

  //storing images into bytearray.

byte[] bFile = baos.toByteArray();

if((bFile [i] & 0xFF) == 0xFF && (bFile[i+1] & 0xFF) == 0xD8 && (bFile[bFile.length - 2] & 0xFF) == 0xFF && (bFile[bFile.length - 1] & 0xFF) == 0xD9)
{
System.out.println("is Image");
}

上面的行只会检查 jpeg 类型,但我想检查其他图像标题的文件扩展名有人可以指出检查其他图像类型究竟需要做什么吗?

谢谢

最佳答案

我做过这样的事情:

/**
* Check if the image is a PNG. The first eight bytes of a PNG file always
* contain the following (decimal) values: 137 80 78 71 13 10 26 10 / Hex:
* 89 50 4e 47 0d 0a 1a 0a
*/
public boolean isValidPNG(InputStream is) {
try {
byte[] b = new byte[8];
is.read(b, 0, 8);
if (Arrays.equals(b, new BigInteger("89504e470d0a1a0a",16).toByteArray())) {
return true;
}
} catch (Exception e) {
//Ignore
return false;
}
return false;
}

/**
* Check if the image is a JPEG. JPEG image files begin with FF D8 and end
* with FF D9
*/
public boolean isValidJPEG(InputStream is, int size) {
try {
byte[] b = new byte[2];
is.read(b, 0, 2);
// check first 2 bytes:
if ((b[0]&0xff) != 0xff || (b[1]&0xff) != 0xd8) {
return false;
}
// check last 2 bytes:
is.skip(size-4);
is.read(b, 0, 2);
if ((b[0]&0xff) != 0xff || (b[1]&0xff) != 0xd9) {
return false;
}
} catch (Exception e) {
// Ignore
return false;
}
return true;
}

/** Check if the image is a valid GIF. GIF files start with GIF and 87a or 89a.
* http://www.onicos.com/staff/iz/formats/gif.html
*/
public boolean isValidGIF(InputStream is) {
try {
byte[] b=new byte[6];
is.read(b, 0, 6);
//check 1st 3 bytes
if(b[0]!='G' || b[1]!='I' || b[2]!='F') {
return false;
}
if(b[3]!='8' || !(b[4]=='7' || b[4]=='9') || b[5]!='a') {
return false;
}
} catch(Exception e) {
// Ignore
return false;
}
return true;
}

还有一个带有一些图片标题的 PHP 主题:PHP : binary image data, checking the image type

关于java - 如何在java中验证图像标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25177795/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com