Skip to content

Instantly share code, notes, and snippets.

@irwinwilliams
Forked from colinMac/ImgToBase64.ps1
Created October 29, 2019 19:15
Show Gist options
  • Save irwinwilliams/6ac32ca039fd06cb175464235130da4c to your computer and use it in GitHub Desktop.
Save irwinwilliams/6ac32ca039fd06cb175464235130da4c to your computer and use it in GitHub Desktop.
Powershell script to convert an image to base64 data uri format and store in a text file
function ImageToBase64 {
Param([String]$path)
[bool]$valid = ($path -ne "")
if ($valid) {
[String[]]$elements = $path.split(".")
[int]$max = $elements.Count - 1
[String]$ext = $elements[$max]
[String]$uri = "data:image/$($ext);base64,"
$elements[$max] = "txt"
[String]$txtPath = $elements -join "."
if (!(Test-Path $path)) {
echo ""
echo "Unable to find image file: $path"
break
}
if ((Test-Path $txtPath)) {
echo ""
echo "Output file already exists: $txtPath, clearing file"
Clear-Content $txtPath
}
}
else {
break
}
[String]$base64 = [convert]::ToBase64String((Get-Content $path -encoding byte))
Write-Output ($uri + $base64) >> $txtPath
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment