Java get image extension from byte array

本秂侑毒 提交于 2020-11-27 08:13:17

问题


I have the below code for saving an image from a byte array.

I am able to save the image successfully using the below code.

Currently I am saving image with ".png" format but I want to get the image extension from byte array and save image with this extension.

Here is my code

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;
}

I am using Java and Tomcat 8.


回答1:


There are many solutions. Very simple for example:

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

Or you can use third-party libraries. Like Apache Tika:

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



回答2:


Would you use the prefix header data:image/png;base64 of the base64 image data?

From the RFC, the "data" url definition:

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

Samples:

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

Then you can get the extension with gif.



来源:https://stackoverflow.com/questions/38452171/java-get-image-extension-from-byte-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!