Created
December 4, 2017 23:22
-
-
Save npotier/2dc4a1b46208344c22fb1b810a2026bb to your computer and use it in GitHub Desktop.
Replace IMG src link tag with IMG embed content encoded in base64
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @author Nicolas Potier <[email protected]> | |
* | |
* Convert img src="" present in HTML page to <img src="data:image..." | |
* This Script is inspired by https://joekuan.wordpress.com/2015/02/01/converting-html-document-with-img-src-link-to-img-embedded-data-in-php/ | |
* | |
* usage : php convert.php source.html destination.html | |
* | |
*/ | |
$srcfilepath = $argv[1]; | |
$dstfilepath = $argv[2]; | |
$srcDir = dirname($srcfilepath); | |
$srcName = basename($srcfilepath); | |
// Read the whole template file into memory | |
if (($template_content = file_get_contents($srcfilepath)) === false) { | |
fprintf($stderr, "Unable to read html file: {$srcfilepath}\n"); | |
return false; | |
} | |
// Match the IMG tag one at a time | |
$offset = 0; | |
while (preg_match('/<img src="([^"]*)"/i', $template_content, $match, PREG_OFFSET_CAPTURE, $offset) >= 1) { | |
$matchTag = $match[0][0]; | |
$matchOffset = $match[0][1]; | |
$imgFile = $srcDir.'/'.$match[1][0]; | |
$ext = pathinfo($imgFile, PATHINFO_EXTENSION); | |
if (!file_exists($imgFile)) { | |
echo "Unable to find image file {$imgFile}\n"; | |
return; | |
} | |
$img_tag = "<img src='data:image/".$ext.";base64," . base64_encode(file_get_contents($imgFile)) . "'"; | |
// Replace the IMG src link tag with IMG embed content | |
$template_content = substr_replace($template_content, $img_tag, $matchOffset, strlen($matchTag)); | |
// offset for next loop | |
$offset = $matchOffset + strlen($img_tag); | |
} | |
file_put_contents($dstfilepath, $template_content); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment