Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 730
dinesh707 Avatar asked Sep 10 '14 10:09

dinesh707


People also ask

What file type is Base64?

Binary file encoded using base64 encoding; often used to convert text data into base64 data; enables more reliable transmission of e-mail attachments and other information; similar to a . MIME attachment.

How do I find Base64 encoded strings?

In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /] . If the rest length is less than 4, the string is padded with '=' characters. ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.

How do I decode a Base64 encoded file?

To decode a file with contents that are base64 encoded, you simply provide the path of the file with the --decode flag. As with encoding files, the output will be a very long string of the original file. You may want to output stdout directly to a file.


2 Answers

if you want to get Mime type use this one

const body = {profilepic:"data:image/png;base64,abcdefghijklmnopqrstuvwxyz0123456789"};
let mimeType = body.profilepic.match(/[^:]\w+\/[\w-+\d.]+(?=;|,)/)[0];

online Demo here

===========================================

if you want to get only type of it like (png, jpg) etc

const body2 = {profilepic:"data:image/png;base64,abcdefghijklmnopqrstuvwxyz0123456789"};
let mimeType2 = body2.profilepic.match(/[^:/]\w+(?=;|,)/)[0];

online Demo here

like image 69
Muhammad Tahir Avatar answered Oct 19 '22 06:10

Muhammad Tahir


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){

    }
}
like image 2
Half Ass Dev Avatar answered Oct 19 '22 08:10

Half Ass Dev