Created
October 31, 2011 21:09
-
-
Save jk3us/1328964 to your computer and use it in GitHub Desktop.
Save images from data: url in an html submission
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Featured here.