Monday, 19 November 2018

searching for and replacing base64 image string with php




I have an HTML string that am getting from the database. The string has several base64 images that i need to replace with an image file which am supposed to generate from the base64 image string. I have no idea how i can do this. Any pointers will be highly appreciated.



original html





intended html





Answer



echo preg_replace_callback('#((?!src=)[^>])*?src=")data:image/(gif|png|jpeg);base64,([\w=+/]++)("[^>]*>)#', "data_to_img", $content);

function data_to_img($match) {
list(, $img, $type, $base64, $end) = $match;

$bin = base64_decode($base64);
$md5 = md5($bin); // generate a new temporary filename
$fn = "tmp/img/$md5.$type";
file_exists($fn) or file_put_contents($fn, $bin);


return "$img$fn$end"; // new tag
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...