10

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.

River
  • 8,585
  • 14
  • 54
  • 67
user3441151
  • 1,880
  • 6
  • 35
  • 79
  • 1
    Possible duplicate of [How to identify contents of a byte\[\] is a jpeg?](http://stackoverflow.com/questions/4550296/how-to-identify-contents-of-a-byte-is-a-jpeg) –  Jul 19 '16 at 07:37
  • 1
    To extend on that: there's a whole list of magic numbers that indicate the file type: https://en.wikipedia.org/wiki/List_of_file_signatures – Thomas Jul 19 '16 at 07:39

2 Answers2

30

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);
Sergey Gornostaev
  • 7,596
  • 3
  • 27
  • 39
0

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.

Adam Deng
  • 408
  • 3
  • 11
  • 2
    There is nothing in the question that tells us that the bytes are Base64 encoded and using a `data:` URL. –  Jul 19 '16 at 08:06