Skip to content

Instantly share code, notes, and snippets.

@mchampaneri
Last active March 6, 2017 09:20
Show Gist options
  • Select an option

  • Save mchampaneri/36539e302167e9b7e027a9bef55738de to your computer and use it in GitHub Desktop.

Select an option

Save mchampaneri/36539e302167e9b7e027a9bef55738de to your computer and use it in GitHub Desktop.
/* * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Get images uploaded with texteditor in base64 format *
* Store this images in disk and replace src value with *
* the url returing the image from the disk *
* * * * * * * * * * * * * * * * * * * * * * * * * * */
function b64toUrl ( $data )
{
// Create blank dom object
$dom = new \DOMDocument();
// Load data in the dom object
$dom->loadHTML($data);
// Searching for the img tag
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
//Getting the value of src attribuite of img
$raw = $image->getAttribute('src');
/* If src tag has value data:image
* than it is upload from device in
* base64 format
*/
if (preg_match('/data:image/', $raw)) {
$name = uniqid();
preg_match('/data:image\/(?<mime>.*?)\;/', $raw, $groups);
$mimetype = $groups['mime'];
$filepath = \Auth::user()->id . '/lectures/images/' . $name . '.' . $mimetype;
// Convert base64 data to the image again
$img = Image::make($raw)
->encode($mimetype, 100);
// Store the image in disk
Storage::put($filepath, $img);
// Remove old src attribute value
$image->removeAttribute('src');
// Set new src attribute value as a url that gives image in response.
$image->setAttribute('src', '/images/' . $filepath);
}
}
// Return the dom html
return $dom->saveHTML();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment