Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java get image extension from byte array

Tags:

java

image

tomcat

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.

like image 876
user3441151 Avatar asked Jul 19 '16 07:07

user3441151


1 Answers

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);
like image 100
Sergey Gornostaev Avatar answered Oct 16 '22 14:10

Sergey Gornostaev