Skip to content

Instantly share code, notes, and snippets.

@mavaddat
Created August 8, 2023 16:24
Show Gist options
  • Save mavaddat/5d331a13bd39e97e763922438df0fc72 to your computer and use it in GitHub Desktop.
Save mavaddat/5d331a13bd39e97e763922438df0fc72 to your computer and use it in GitHub Desktop.
Convert all images to base64
$md = <# PATH TO MARKDOWN FILE #>
$images = Select-String -Pattern "(?<=!\[[^\(]+\()[^\)]+(?=\))" -Path $md | ForEach-Object { $_.Matches.Value }
$html = <# PATH TO HTML FILE #>
$images = Select-String -Pattern "(?<=src=`")[^`"]+(?=\))" -Path $html | ForEach-Object { $_.Matches.Value }
$imagesBase64 = [string[]]::new($images.Count)
foreach($image in $images){
try {
# $filehandle = [System.IO.File]::Open((Join-Path -Path (Split-Path -Path $md -Parent) -ChildPath $image),[System.IO.FileMode]::Open)
$filehandle = [System.IO.File]::Open($image,[System.IO.FileMode]::Open)
$bytes = [byte[]]::new($filehandle.Length)
$filehandle.Read($bytes,0,$filehandle.Length) | Out-Null
}
finally {
$filehandle.Dispose()
}
$base64 = [System.Convert]::ToBase64String($bytes)
$i = $images.IndexOf($image)
$imagesBase64[$i] = "data:image/png;base64,$base64"
$base64 = $null
}
Get-Content -Path $html | ForEach-Object {
$line = $_
foreach($image in $images){
$imagePattern = "(?<=src=`").*$([regex]::Escape($image))"
if($line -match $imagePattern) {
$i = $images.IndexOf($image)
$line = $line -replace $imagePattern, ($imagesBase64[$i])
}
}
$line | Write-Output
} | Out-File $env:TEMP\uow.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment