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.
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);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With