Validating Base64 Encoded Images

Validating base64 encoded images

One way of doing this would be to actually create an image file from the base64 data, then verify the image itself with PHP. There might be a simpler way of doing this, but this way should certainly work.

Keep in mind that this only really works for PNGs, you'll need to add some logic if you're planning on allowing more file types (GIF, JPG).


$base64 = "[insert base64 code here]";
if (check_base64_image($base64)) {
print 'Image!';
} else {
print 'Not an image!';

function check_base64_image($base64) {
$img = imagecreatefromstring(base64_decode($base64));
if (!$img) {
return false;

imagepng($img, 'tmp.png');
$info = getimagesize('tmp.png');


if ($info[0] > 0 && $info[1] > 0 && $info['mime']) {
return true;

return false;


Python - Is Base64 data a valid image?

The PNG format has a fixed header that consists of the 8 bytes 89 50 4e 47 0d 0a 1a 0a which, when converted to base64, look like this:


As you can see, it ends with a padding character "=", which will not be there in a real base64 representation of an image, and instead of "o" there could be a different character depending on the bytes after the header.

So you can easily recognize a base64 encoded PNG by comparing the first characters of the base64 string with


This principle works for all file formats that have a fixed header.

Validating a base64 encoded image .NET core

When you don't have System.Drawing I would look at the actual bytes instead to see if they match the JPEG or PNG file standard.

For a PNG file the first eight bytes always contains the following decimal values: 137 80 78 71 13 10 26 10 (Source)

A JPEG file is more complex but it can be done as well. The first two bytes, at least, seems to always be 0xFF 0xD8 (Source). Read a bit more about the file structure to get better comparison values.

Based on this you can do a simple comparison on the bytes in your imageBytes array.

How to validate base 64 string with Laravel 4.2


 if (!base64_decode($value))

base64_decode will return false on non base64 string.

Related Topics

Leave a reply