Let' say a file (e.g. myfile.jpeg) encoded in Base64 String and given to me. There is no way I know what the file type was. I'd like to decode the string into a file (an image in this example). How do I know the type of the file (e.g jpeg)?
If you have a base64 string you can detect file type by checking the first character of your base64 string: '/' means jpeg. 'i' means png. 'R' means gif.
To decode with base64 you need to use the --decode flag. With encoded string, you can pipe an echo command into base64 as you did to encode it. Using the example encoding shown above, let's decode it back into its original form. Provided your encoding was not corrupted the output should be your original string.
Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. By consisting only of ASCII characters, base64 strings are generally url-safe, and that's why they can be used to encode data in Data URLs.
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.
In general, a base 64-encoded string could contain absolutely any data, so there is no way to know its file type.
To determine if it is an instance of a JPEG image, you'd need to base64-decode it, and then do something like checking its magic number, which is useful in telling you what the file isn't. You'd still need to do more work to determine if it is a valid JPEG image.
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAMSURBVBhXY/j//z8ABf4C/qc1gYQAAAAASUVORK5CYII=
Is a sample image. Just split it with the first slash and get array index 1. Supposing the image is coming from a trusted client.
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