Java从字节数组中获取图像扩展名

标签 java image tomcat

我有以下代码用于从字节数组保存图像。

我可以使用以下代码成功保存图像。

目前我正在以“.png”格式保存图像,但我想从字节数组中获取图像扩展名并使用此扩展名保存图像。

这是我的代码

public boolean SaveImage(String imageCode) throws Exception {
    boolean status = false;
    Connection dbConn = null;
    CallableStatement callableStatement = null;
    try {
        String base64Image = imageCode.split(",")[1];
        byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);

        Properties propFile = LoadProp.getProperties();
        String filepath = propFile.getProperty(Constants.filepath);
        File file = new File(filepath + "xyz.png");
        FileOutputStream fos = new FileOutputStream(file);
        try {
            fos.write(imageBytes);
        } finally {
            fos.close();
        }
    } catch (Exception e) {
        throw e;
    } finally {
        if (callableStatement != null) {
            callableStatement.close();
        }
        if (dbConn != null) {
            dbConn.close();
        }
    }
    return status;
}

我正在使用 Java 和 Tomcat 8。

最佳答案

有很多解决方案。非常简单的例子:

String contentType = URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(imageBytes));

或者您可以使用第三方库。喜欢Apache Tika :

String contentType = new Tika().detect(imageBytes);

关于Java从字节数组中获取图像扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38452171/

相关文章:

javascript - 将图像可见性设置为 false

javascript - 使用 d3js 将图像放置在网格中

tomcat - 设置 Tomcat 7 和 NetBeans/Eclipse

Java线程栈内存占用

java - 如何在动态加载的 jar 中模拟方法

java - 我可以在我的java代码中使用两个ssh java lib吗?

flutter - 显示数据库中的图像,该图像在 flutter 的路径中具有反斜杠而不是斜杠

java - Freemarker:迭代哈希中的嵌套列表

java - YUV_420_888 到 RGB 转换

tomcat - 无法连接到部署在 Tomcat 中的 ServerEndpoint