【问题标题】:How to validate image header in java如何在java中验证图像头
【发布时间】:2014-09-30 09:59:22
【问题描述】:

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

我正在使用请求附带的 mimeType,但如果我正在加载重命名为 .jpg 文件的 .txt 文件,那么它也会显示图像/jpg 的 mime-type,基本上我不想上传这些文件.现在我想确保没有人能够上传在 .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 类型,但我想检查其他图像头的文件扩展名 有人可以指出检查其他图像类型需要做什么吗?

谢谢

【问题讨论】:

标签: java image file mime-types magic-numbers


【解决方案1】:

我做过类似的事情:

/**
 * 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

【讨论】:

  • 你的方法 isValidPNG 帮助了我,但我不得不改变一些东西。不知何故,您从该 BigInteger 创建的字节数组包含 9 个字节,而不是 8 个字节,其中第一个字节的值为零。我不得不砍掉它(通过将“错误”字节数组包装在 Arrays.copyOfRange(byteArray, 1, 9) 中。
猜你喜欢
  • 2013-03-10
  • 2021-04-06
  • 2015-03-02
  • 2021-07-17
  • 2021-06-28
  • 2013-07-30
  • 1970-01-01
  • 1970-01-01
  • 2010-10-03
相关资源
最近更新 更多