Pab*_*dez 5 java mysql blob detection mime-types
是的我知道我们不应该将图像存储在数据库中,谢谢.
那说,有没有办法在java中检测存储在mysql中的BLOB的mime类型?
它只适用于图像(.gif,.png,.jpeg等)我不需要通用的工具.
非常感谢你们
如果建议的解决方案不涉及第三方库,则奖励积分:)
我想你可以看一下标题。您需要将数据读入字节数组,然后检查字节以查看它们是否与不同文件类型的标头匹配。
例如,对于 GIF,前三个字节是“GIF”(47 16 49 16 46 16 ),后跟“87a”(38 16 37 16 61 16 ) 或“89a”(38 16 39 16 61 16 )。
所以类似这样的东西应该可以工作(使用 a用于演示目的,但您可以使用orFileInputStream从 BLOB 获取二进制数据):ResultSet#getBinaryStream(int)ResultSet#getBinaryStream(String)
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
public class IdentifyImage {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
try {
in = new FileInputStream("sample.gif");
//The following are in base 10
byte[] gifHeader87a = {71, 73, 70, 56, 55, 97};
byte[] gifHeader89a = {71, 73, 70, 56, 57, 97};
byte[] bytes = new byte[6];
in.read(bytes, 0, 6);
if(Arrays.equals(gifHeader89a, bytes) || Arrays.equals(gifHeader87a, bytes)) {
System.out.println("It's a GIF!");
}
} finally {
if (in != null) {
in.close();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您只需在标头中查找其他文件类型(如 JPG、PNG 等)的字节即可。不确定这是否是最好的方法。有人可能有更好的解决方案。
就第 3 方库而言,jMimeMagic相当不错。这可能是最简单的解决方案:)。
编辑
我在这里找到了这篇文章,其中列出了不同文件类型的标头信息。有一些示例代码,但它是用另一种语言(Clarion)编写的。