Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

Created January 20, 2012 17:19
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/1648519 to your computer and use it in GitHub Desktop.
Save anonymous/1648519 to your computer and use it in GitHub Desktop.
Save images from clipboard with tinymce
<?php
function save_images($object_id, $string, $overwrite=false) {
if (!function_exists('imagecreatefromstring')) {
throw new \Exception("This script requires the imagecreatefromstring function from the GD extension (http://www.php.net/manual/en/book.image.php).");
}
// 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');
$usedFilenames = array();
for ($i = 0; $i < $items->length; $i++) {
$src = $items->item($i)->getAttribute('src');
$alt = $items->item($i)->getAttribute('alt');
// 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 = __DIR__."/saved/$object_id";
if (!file_exists($path)) {
mkdir($path, 0775);
}
if (empty($alt)) $filename = $md5;
else $filename = urlencode(str_replace(' ', '_', strtolower(substr($alt, 0, 30))));
if (in_array($filename, $usedFilenames)) {
$filename .= '_'.$md5;
}
$usedFilenames[] = $filename;
//convert image to JPG
$imgDataFromClipboard = imagecreatefromstring($data);
if ($imgDataFromClipboard) {
$path .= "/{$filename}.jpg";
//save as JPG
if ($overwrite || !file_exists($path)) {
imagejpeg($imgDataFromClipboard, $path, 90); //90% quality
}
}
else {
throw new \Exception("Error retrieving image data");
}
$items->item($i)->setAttribute('src', "{$object_id}/{$filename}.jpg");
}
}
$string = $DOM->saveHTML();
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment