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

标签 java image file mime-types magic-numbers

我有一个可用于上传文件的网页。 现在我需要检查图像文件类型是否正确,如 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/

相关文章:

java - 在 NeoMAD 项目中使用 java.util.Iterator 时出错

java - 添加与另一个数组中的值长度相同的数组?

arrays - 如何解决 Java heap space Exception for ArrayList Size?

java - 使用机器人类截取屏幕截图 - 希望减少文件大小

java - 使用 Spring 测试 Dao

c++ - 我如何使用 Qt 查看大图像?

image - SVG 不支持图像的自动宽度和高度吗?

php - 为 VPS 上的大多数用户替换文件(在相同的相对路径)

c# - 从文件夹中选择随机文件

c# - 从目录中获取文件数而不在 C# 中枚举文件