Skip to content

Instantly share code, notes, and snippets.

@pkcpkc
Last active August 9, 2019 19:06
Show Gist options
  • Save pkcpkc/0d01275f15641916d498cf8b1049578a to your computer and use it in GitHub Desktop.
Save pkcpkc/0d01275f15641916d498cf8b1049578a to your computer and use it in GitHub Desktop.
Replace all local images references in HTML with base64 inline data, e.g. for HTML emails
#!/bin/bash
# Searches for <img src="localImage" alt="altText"/> in index.html and replaces with:
# <img src="data:image/png;base64,..." alt="altText"/>
# writes output to build/index.html
mkdir -p build
# awk is really awkward: does not accept regexp groups :(
# I'll keep the () anyways for my mental health!
awk -F'"' -v q="'" '/<img src=\"(.*)\" alt=\".*\"\/>/ {
cmd=sprintf("openssl enc -base64 -in \"%s\" | tr -d %c\\n%c",$2,q,q)
cmd | getline b64
close(cmd)
$0=$1 "\"data:image/png;base64," b64 "\" alt=\"" $4 "\"/>"
}1' index.html >build/index.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment