I have a data uri and I need to get an img tag out of it that references some url.
Why would I want to do that?
I'm developing an extension that contains an overlay over Google Docs and displays an image inside of it. The user should then be able to drag that image into the document to use it. If I include the image via a normal url to some stock photo, everything works perfectly. However, if I include the image via a data uri, Google Docs fails to load that image.
My idea for a solution:
<img src="http://some-imaginary-host.org/getpng/?data=data:image/png;base64,iVBORw0K...">
This image tag would contain a loadable url that returns a standard .png file. That host wouldn't have to store any data, just do the basic (I hope) conversion and correct headers.
Now my questions:
So here's my solution:
Steps:
Server converts data uri to correct url (code below)
Chrome Extension Script inserts the image by manually opening dialogs (this is honestly the best thing I could come up with, even though it's bad everything else didn't work..)
Server script:
<?php
// NOTE: This code is far from perfect, but it does the job (at least in my own-use case)
// NOTE: Parameter has to be sanitized before sending, to avoid url-escaping
// Validate the parameter
if(!preg_match('/data:(.*_.*;base64,[a-zA-Z0-9._-]*)/', $_GET["data"])) {
die("Not a valid parameter.");
}
// Decode the received url-safe data into valid base64
$convertedUri = strtr($_GET["data"], "._-", "+/=");
// Split the data uri into parts
$uri = explode(";", $convertedUri);
$contentType = explode(":", $uri[0])[1];
$base64 = explode(",", $uri[1])[1];
$data = base64_decode($base64);
// Try to convert the received data into an image
$im = imagecreatefromstring($data);
if ($im !== false) {
header('Content-Type: '.$contentType);
echo $data;
imagedestroy($im);
}
else {
die("Error: " . $base64);
}
?>