Convert image to base64 php

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

asked Oct 19, 2010 at 10:44

Volatil3Volatil3

13.3k37 gold badges126 silver badges245 bronze badges

3

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];

kenorb

144k76 gold badges654 silver badges709 bronze badges

answered Dec 7, 2012 at 7:29

Ronny ShererRonny Sherer

7,9691 gold badge21 silver badges9 bronze badges

5

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.

answered Oct 19, 2010 at 10:45

1

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 '';

answered Sep 11, 2013 at 11:20

Raju RamRaju Ram

8939 silver badges14 bronze badges

1

Just in case you are [for whatever reason] unable to use curl nor file_get_contents, you can work around:

$img = imagecreatefrompng['...'];
ob_start[];
imagepng[$img];
$bin = ob_get_clean[];
$b64 = base64_encode[$bin];

answered May 22, 2016 at 5:12

yckartyckart

30.8k9 gold badges117 silver badges127 bronze badges

0

Chủ Đề