【问题标题】:Java get image extension from byte arrayJava从字节数组中获取图像扩展名
【发布时间】:2016-07-19 07:34:08
【问题描述】:

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

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

目前我正在以“.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。

【问题讨论】:

标签: java image tomcat


【解决方案1】:

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

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

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

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

【讨论】:

  • 这仅适用于 jpg 图像的 png 图像,它也作为 png 扩展名提供
【解决方案2】:

你会使用base64图像数据的前缀标题data:image/png;base64吗?

来自 RFC,“数据” url 定义:

### Form : `data:[<mediatype>][;base64],<data>`
### Syntax:
`dataurl   := "data:" [ mediatype ] [ ";base64" ] "," data
mediatype:= [ type "/" subtype ] *( ";" parameter )
data       := *urlchar
parameter  := attribute "=" value`

样品:

data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP///ywAAAAAMAAw......

然后就可以用gif获取扩展了。

【讨论】:

  • 问题中没有任何内容告诉我们字节是 Base64 编码并使用data: URL。
猜你喜欢
  • 1970-01-01
  • 2018-06-18
  • 1970-01-01
  • 2012-04-19
  • 2012-07-11
  • 2021-02-02
  • 1970-01-01
  • 2016-09-20
  • 1970-01-01
相关资源
最近更新 更多