Skip to content

Instantly share code, notes, and snippets.

@jk3us
Created October 31, 2011 21:09
Show Gist options
  • Select an option

  • Save jk3us/1328964 to your computer and use it in GitHub Desktop.

Select an option

Save jk3us/1328964 to your computer and use it in GitHub Desktop.
Save images from data: url in an html submission
function save_images($object_id, $string) {
// This part could probably be better
$types = array(
'image/jpeg' => 'jpg',
'image/png' => 'png',
'image/gif' => 'gif',
);
$DOM = new DOMDocument;
$DOM->loadHTML($string);
// Find all the img tags
$items = $DOM->getElementsByTagName('img');
for ($i = 0; $i < $items->length; $i++) {
$src = $items->item($i)->getAttribute('src');
// Only the ones with data: urls
if (preg_match('/^data:/',$src)) {
// Deconstruct it, get all the parts
$semicolon_place = strpos($src, ';');
$comma_place = strpos($src, ',');
$type = substr($src,5,$semicolon_place-5);
$base64_data = substr($src, $comma_place+1);
$data = base64_decode($base64_data);
$md5 = md5($data);
$path = "/full/path/to/object/$object_id"
if (!file_exists($path)) {
mkdir($path, 0775);
}
$path .= "/{$md5}.{$types[$type]}";
if (!file_exists($path)) {
$handle = fopen($path,'w');
fwrite($handle, $data);
fclose($handle);
}
$items->item($i)->setAttribute('src', "/web/path/to/{$object_id}/{$md5}.{$types[$type]}");
}
}
$string = $DOM->saveHTML();
return $string;
}
@jk3us
Copy link
Copy Markdown
Author

jk3us commented Oct 31, 2011

Featured here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment