rapoli
rapoli

Reputation: 15

Convert API URL to “data:image/png;base64" by PHP

The following API URL has an output in PNG image:

http://qrfree.kaywa.com/?l=1&s=8&d=google.com

I want convert the API URL to “data:image/png;base64” (DATA URL / DATA URI) with the similar to the PHP code example below:

$image = ("<img src = http://qrfree.kaywa.com/?l=1&s=8&d=google.com"); // False! (only example!)
//or
$image = 'real-picture.png'; // True!

$imageData = base64_encode(file_get_contents($image));
$src = 'data:image/png;base64,'.$imageData;
echo '<img src="'.$src.'">';

However, the above code works with a real picture which has specified format and if replaced with the API URL, cannot read image path. How the code should be corrected?

Upvotes: 1

Views: 1251

Answers (1)

CodeBoy
CodeBoy

Reputation: 3300

Assuming a web request to http://qrfree.kaywa.com/?l=1&s=8&d=google.com returns an image of type image/png, you can do ...

$image = "http://qrfree.kaywa.com/?l=1&s=8&d=google.com";
echo '<img src="data:image/png;base64,', 
    base64_encode(file_get_contents($image)),
    '">';

file_get_contents() expects either a valid file name or a valid http(s) request. Your code was passing in something starting with some HTML <img ...

Upvotes: 3

Related Questions