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

use*_*151 7 java tomcat image

我有以下代码用于保存字节数组中的图像.

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

目前我正在使用".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;
}
Run Code Online (Sandbox Code Playgroud)

我正在使用Java和Tomcat 8.

Ser*_*aev 17

有很多解决方案.非常简单,例如:

String contentType = URLConnection.guessContentTypeFromStream(new ByteArrayInputStream(imageBytes));
Run Code Online (Sandbox Code Playgroud)

或者您可以使用第三方库.像Apache Tika一样:

String contentType = new Tika().detect(imageBytes);
Run Code Online (Sandbox Code Playgroud)