Skip to content

Instantly share code, notes, and snippets.

@nmfzone
Last active September 19, 2021 18:55
Show Gist options
  • Select an option

  • Save nmfzone/036585c441545a2e4c2e423b5da3a4f3 to your computer and use it in GitHub Desktop.

Select an option

Save nmfzone/036585c441545a2e4c2e423b5da3a4f3 to your computer and use it in GitHub Desktop.
Image Extractor from WYSIWYG
<?php
namespace Spark\Utility;
use Closure;
use Illuminate\Support\Str;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\HttpFoundation\File\File;
class ImageExtractor
{
/**
* Extract image from html string and uploads.
*
* @param string $html
* @param string|\Closure $uploader
* @param \Closure $replacer
* @return string
*
* @throws \Exception
*/
public static function htmlExtractAndUploads(string $html, $uploader, Closure $replacer = null)
{
$crawler = new Crawler($html);
$imageTags = $crawler->filterXPath('//img')->images();
if (is_string($uploader)) {
$path = public_path($uploader);
if (! file_exists($path)) {
@mkdir($path, $permission, true);
}
}
foreach ($imageTags as $imageTag) {
$base64Path = $imageTag->getUri();
$image = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $base64Path));
$tmpFilePath = tmp_path(Str::uuid()->toString());
file_put_contents($tmpFilePath, $image);
$file = new File($tmpFilePath);
$imgName = Str::uuid()->toString() . '.' . $file->guessExtension();
if ($uploader instanceof Closure) {
$path = $uploader($file, $imgName);
} else {
$path = $uploader . '/' . $imgName;
$file->move(public_path($uploader), $imgName);
}
$replacer = $replacer instanceof Closure ? $replacer($path) : url($path);
$html = str_replace($base64Path, $replacer, $html);
}
return $html;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment