I am interested in requesting an image through HTTP with PHP, then converting the image to a data URI. How would I go about doing this?
For example:
$img = file_get_contents("http://something.com/something.png");
$datauri = magicalfunction($img);
echo("<img src=\"$datauri\" />");
I know I used file_get_contents()
there, but I would prefer a solution that doesn't use the file functions. If possible, I'd like to use cURL.
The data URI is composed by the literal data:
, then the media type (defaults to text-plain if omitted), ;base64
if you are encoding (which you should, if you have binary data as an image), and then the data itself.
Linky to some docs.
You could do it like this:
// Your image
$image = 'crazy_cat.jpg';
$myvar = file_get_contents($image);
function srcData($image)
{
$finfo = finfo_open(FILEINFO_MIME_TYPE);
// reads your image's data and convert it to base64
$data = base64_encode($image);
// Create the image's SRC: "data:{mime};base64,{data};"
return 'data: ' . finfo_buffer($finfo, $image) . ';base64,' . $data;
}
echo "<img src='" . srcData($myvar) . "'/>";
Ta da!
If you are downloading the image before serving it like data
, you'd have to do it before calling this function, and pass the function the buffer containing the file.
For bonus points: the "how to use curl" can be summarized thus:
$ch = curl_init('http://placekitten.com.s3.amazonaws.com/homepage-samples/408/287.jpg');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$myvar = curl_exec($ch);
curl_close($ch);
And you'll have your image in $myvar
, ready to pass to srcData()
.