Get Image Type from Base64 Encoded Src String

Get image type from base64 encoded src string

Well you have basically two options:

  1. Trust the metadata
  2. Type check the image source directly

Option 1:

Probably the quicker way because it only involve splitting string, but it may be incorrect.
Something like:

$data = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA.';
$pos = strpos($data, ';');
$type = explode(':', substr($data, 0, $pos))[1];

Option 2:

Use getimagesize() and it's equivalent for string:

$info = getimagesizefromstring(explode(',', base64_decode($data)[1], 2));
// $info['mime']; contains the mimetype

Detecting image type from base64 string in PHP

FileInfo can do that for you:

$encoded_string = "....";
$imgdata = base64_decode($encoded_string);

$f = finfo_open();

$mime_type = finfo_buffer($f, $imgdata, FILEINFO_MIME_TYPE);

Javascript - get extension from base64 image

For a String (which you can parse out of an image) you can do this:

// Create Base64 Object
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

// Define the string, also meaning that you need to know the file extension
var encoded = "Base64 encoded image returned from your service";

// Decode the string
var decoded = Base64.decode(encoded);
console.log(decoded);

// if the file extension is unknown
var extension = undefined;
// do something like this
var lowerCase = decoded.toLowerCase();
if (lowerCase.indexOf("png") !== -1) extension = "png"
else if (lowerCase.indexOf("jpg") !== -1 || lowerCase.indexOf("jpeg") !== -1)
extension = "jpg"
else extension = "tiff";

// and then to display the image
var img = document.createElement("img");
img.src = decoded;

// alternatively, you can do this
img.src = "data:image/" + extension + ";base64," + encoded;

For completion's sake here's the source and I hope this helps!

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

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

}
}

How to get MIME-TYPE from Base 64 String?

You can use magic numbers to detect a MIME type (check here the list of file signatures). However, file signatures are not 100% reliable and you can easily encounter false positives. Of course, there are tasks when a such solution is more than enough.

So if you have a Base64 string and want to identify its MIME type using file signatures you don't need to decode the Base64. A much faster way is to store the file signatures as Base64 and just check if input starts with one of them. A simple example:

var signatures = {
JVBERi0: "application/pdf",
R0lGODdh: "image/gif",
R0lGODlh: "image/gif",
iVBORw0KGgo: "image/png",
"/9j/": "image/jpg"
};

function detectMimeType(b64) {
for (var s in signatures) {
if (b64.indexOf(s) === 0) {
return signatures[s];
}
}
}

// Some tests
console.log(detectMimeType('R0lGODdhAQABAPAAAP8AAAAAACwAAAAAAQABAAACAkQBADs='));
console.log(detectMimeType('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR42mP4z8AAAAMBAQD3A0FDAAAAAElFTkSuQmCC'));
console.log(detectMimeType('JVBERi0xLjUKJYCBgoMKMSAwIG9iago8PC9GaWx0ZXIvRmxhdGVEZWNvZGUvRmlyc3QgMTQxL04gMjAvTGVuZ3'));
console.log(detectMimeType('/9j/4AAQSkZJRgABAQAAZABkAAD/2wCEABQQEBkSGScXFycyJh8mMi4mJiYmLj41NTU1NT5EQUFBQUFBRERERERERERE'));

How to get base64 img src and insert it into input.files

You need convert base64 image to file, then use DataTransfer to recivie the file. You can try my sample code like below.

@{
ViewData["Title"] = "Home Page";
}
@model Net5_MVC.Controllers.HomeController.mainImageInput
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script>
function dataURLtoFile(dataurl, filename) {

var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);

while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}

return new File([u8arr], filename, { type: mime });
}
function ConvertClick(base64url) {
var file = dataURLtoFile(base64url, "test.png");
let container = new DataTransfer();
container.items.add(file);
document.querySelector('#mainImageInput').files = container.files;
var newfile = document.querySelector('#mainImageInput').files[0];
}
</script>

<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>

<img id="mainImage" style="width:200px;height:160px" src="@Model.ImageInBase64">

<input asp-for="Image" id="mainImageInput" style="display:none" type="file" accept="image/jpeg, image/png" class="form-control" />
<button onclick="ConvertClick('@Model.ImageInBase64')">Convert</button>

Test Result:

Sample Image

Get the file extension of a base64 encoded string

Here is a one-liner inspired by @msg's answer:

$extension = explode('/', mime_content_type($base64_encoded_string))[1];

Is there a type for base64 encoded images in Typescript?

I don't think there is, but you can create your own type that is an alias for a string type, So when you look at your code you can disambiguate between regular string and your base type.

type Base64 = string
mainImage: Schema.Post["mainImage"] & {
lqip: Base64
}


Get filetype from BASE64 file

You could write the base64 content into BytesIO:

import base64
import magic # https://pypi.org/project/python-magic/
import io

data = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+P+/HgAFhAJ/wlseKgAAAABJRU5ErkJggg=='

bytesData = io.BytesIO()
bytesData.write(base64.b64decode(data))
bytesData.seek(0) # Jump to the beginning of the file-like interface to read all content!
print(magic.from_buffer(bytesData.read()))

Out:

PNG image data, 1 x 1, 8-bit/color RGBA, non-interlaced

How to get file extension from base64 String in Flutter | Dart

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.

'U' means webp.

'J' means PDF.

I wrote a function for that:

String getBase64FileExtension(String base64String) {
switch (base64String.characters.first) {
case '/':
return 'jpeg';
case 'i':
return 'png';
case 'R':
return 'gif';
case 'U':
return 'webp';
case 'J':
return 'pdf';
default:
return 'unknown';
}
}


Related Topics



Leave a reply



Submit