Java gets image extension from byte array

I have the following code to save an image from an array of bytes.

I can successfully save the image using the code below.

I am currently saving the image with the ".png" format, but I want to get the image extension from the byte array and save the image using 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.

+4
source share
2 answers

There are many solutions. Very simple:

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

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

String contentType = new Tika().detect(imageBytes);
+8
source

data:image/png;base64 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.

0

Source: https://habr.com/ru/post/1648337/


All Articles