[Solved] How to save binary images to wordpress upload directory

Many times, when we use an editor for example, Summernote, and we upload a media then it returns the html with biary images. If the images are large in size, then binary data also exceedes, so the content cannot be loaded in the wp-admin and hangs the browser, so we need to save binary images to wp upload directory.

To save binary images, we need to use DOM library, but we have to also use some important flags to save images flawlessly. Using this function save_binary_images, you can save all the binary images present in the content. You may also provide prefix to the name of images, just by providing value of $image_prefix. You can see the below code and just copy and paste to save binary images to wp upload directory :

$content = save_binary_images($_POST[‘content’],’idea_’.$post_id);

//save binary image to folder
function save_binary_images($html,$image_prefix=”){
$upload_dir = wp_upload_dir();
$email_img = ”;
if( wp_mkdir_p( $upload_dir[‘path’] ) ) {
$path = $upload_dir[‘path’] . ‘/’;
$url = $upload_dir[‘url’];
} else {
$path = $upload_dir[‘basedir’] . ‘/’;
$url = $upload_dir[‘baseurl’];
}

$doc = new DOMDocument(); $images=array();

//Important to use LIBXML_HTML_NOIMPLIED because it sets HTML_PARSE_NOIMPLIED flag, which turns off the automatic adding of implied html/body… elements.

// Important to use LIBXML_HTML_NODEFDTD because it sets HTML_PARSE_NODEFDTD flag, which prevents a default doctype being added when one is not found.
$doc->loadHTML(mb_convert_encoding((preg_replace(‘/\\\\/’, ”, $html)), ‘HTML-ENTITIES’, ‘UTF-8’), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$imageTags = $doc->getElementsByTagName(‘img’);
if($imageTags){
foreach($imageTags as $tag) {
$src = $tag->getAttribute(‘src’);
if(strpos($src, ‘data:image’)!==false){
$src = base64_decode(preg_replace(‘#^data:image/\w+;base64,#i’, ”, $src));
$filename = $image_prefix.’_’.rand().’.png’;
if(file_put_contents($path.$filename, $src)!==false){
$img_url = $url.’/’.$filename;
$img = $doc->createElement(‘img’);
$img->setAttribute(“src”,$img_url);
$tag->parentNode->replaceChild($img, $tag);
}
}
}
}
$content = $doc->saveHTML();
return $content;
}

Now, you can save the $content of post which contains images which are saved in wp upload directory instead of binary images.

Leave a Reply