如何在java中验证图像头

Uda*_*uru 3 java image file magic-numbers mime-types

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

我正在使用请求附带的mimeType,但如果我正在加载重命名为.jpg文件的.txt文件,那么也是mime-type它显示图像/ 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");
                    }
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Ath*_*nor 8

我做过类似的事情:

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)

还有一个带有一些图像标题的PHP主题:PHP:二进制图像数据,检查图像类型