Search code examples
javaimagemime-types

How to identify file type by Base64 encoded string of a image


I get a file which is Base64 encoded string as the image. But I think the content of this contains information about file type like png, jpeg, etc. How can I detect that? Is there any library which can help me here?


Solution

  • I have solved my problem with using mimeType = URLConnection.guessContentTypeFromStream(inputstream);

    { //Decode the Base64 encoded string into byte array
     // tokenize the data since the 64 encoded data look like this "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAoAAAAKAC"
    
        String delims="[,]";
        String[] parts = base64ImageString.split(delims);
        String imageString = parts[1];
        byte[] imageByteArray = Base64.decode(imageString );
    
        InputStream is = new ByteArrayInputStream(imageByteArray);
    
        //Find out image type
        String mimeType = null;
        String fileExtension = null;
        try {
            mimeType = URLConnection.guessContentTypeFromStream(is); //mimeType is something like "image/jpeg"
            String delimiter="[/]";
            String[] tokens = mimeType.split(delimiter);
            fileExtension = tokens[1];
        } catch (IOException ioException){
    
        }
    }