How to convert an image to Base64 encoding

How can I convert an image from a URL to Base64 encoding?


Solution 1:

I think that it should be:

$path = 'myfolder/myimage.png';
$type = pathinfo($path, PATHINFO_EXTENSION);
$data = file_get_contents($path);
$base64 = 'data:image/' . $type . ';base64,' . base64_encode($data);

Solution 2:

Easy:

$imagedata = file_get_contents("/path/to/image.jpg");
             // alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);

Bear in mind that this will enlarge the data by 33%, and you'll have problems with files whose size exceed your memory_limit.

Solution 3:

Also use this way to represent an image in Base64-encoded format...

Find the PHP function file_get_content and next use the function base64_encode.

And get the result to prepare str as data:" . file_mime_type . " base64_encoded string. Use it in the img src attribute. The following code ma be helpful:

// A few settings
$img_file = 'raju.jpg';

// Read image path, convert to base64 encoding
$imgData = base64_encode(file_get_contents($img_file));

// Format the image SRC:  data:{mime};base64,{data};
$src = 'data: '.mime_content_type($img_file).';base64,'.$imgData;

// Echo out a sample image
echo '<img src="'.$src.'">';