Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<#
.SYNOPSIS
Adds a Base64 encoded string to CSV file
.DESCRIPTION
Looks for URL/URI/PATH column in CSV file.
Encodes the image in URI to Base64 string.
Creates a new column 'Encoded' with Base64 string
Column values can be http/https url or path to local file
Encode functions adapted from https://gist.github.com/brunolm/ceefbf4ee61da63fad5f004db96c5c82
.EXAMPLE encode-base64-url.ps1 "C:\data\imageUrls.csv"
#>
function Get-ImageBase64([string]$file) {
if ($file -like 'http*') {
return Get-ImageBase64FromUrl($file);
}
return Get-ImageBase64FromFile($file);
}
function Get-ImageBase64FromFile(
[string]
[ValidateScript( { Test-Path $_ })]
$file
) {
$type = Get-MimeType $file;
$base64 = [convert]::ToBase64String((Get-Content $file -Encoding byte));
return "data:$type;base64,$base64";
}
function Get-ImageBase64FromUrl([Uri]$url) {
$b = Invoke-WebRequest $url;
$type = $b.Headers["Content-Type"];
$base64 = [convert]::ToBase64String($b.Content);
return "data:$type;base64,$base64";
}
function Get-MimeType($CheckFile) {
Add-Type -AssemblyName "System.Web"
[System.IO.FileInfo]$checkFile = $CheckFile
$mime_type = ''
if ($checkFile.Exists) {
$mime_type = [System.Web.MimeMapping]::GetMimeMapping($checkFile.FullName);
}
return $mime_type;
}
function Write-Red {
process { Write-Host $_ -ForegroundColor Red }
}
function Encode-Csv($csvPath) {
$csvFile = Get-Item -Path $csvPath
$csvEncodedPath = Join-Path $csvFile.DirectoryName "$($csvFile.BaseName)_encoded.csv"
$csv = Import-Csv -Path $csvPath
$headers = ($csv | Get-Member -MemberType NoteProperty).Name
if('uri' -in $headers -Or 'url' -in $headers -Or 'path' -in $headers){
ForEach ($row in $csv)
{
# Pick first non-null value
$uri = (@($row.url, $row.uri, $row.path) -ne $null)[0]
try{
$encoded = Get-ImageBase64($uri)
$row | Add-Member -MemberType NoteProperty -Name 'Encoded' -Value $encoded
}
catch {
Write-Output "Error processing URI: $uri" | Write-Red
}
}
$csv | Export-Csv -Path $csvEncodedPath -NoTypeInformation
}
else {
Write-Output "uri/url/path column missing" | Write-Red
}
}
if ($args.count -eq 0) {
Write-Output "File path missing" | Write-Red
}
else {
Encode-Csv($args[0])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment