Skip to content

Instantly share code, notes, and snippets.

@pferreirafabricio
Last active March 30, 2024 15:44
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pferreirafabricio/97c1c68057e406ff0f98840659973f0d to your computer and use it in GitHub Desktop.
Save pferreirafabricio/97c1c68057e406ff0f98840659973f0d to your computer and use it in GitHub Desktop.
🖼 Convert an image to a Base64 string with PowerShell
<#
OBS:
The AsByteStream parameter was introduced in Windows PowerShell 6.0
If your PowerShell version (run `(Get-Host).Version` to find out) is lower than 6 then use the version for Powershell 5.1:
#>
$pathToImage = "/home/user/development/image.png"
# For Powershell 5.1
[String]$base64 = [convert]::ToBase64String((Get-Content $pathToImage -Raw -Encoding Byte))
# For Powershell 6+
[String]$base64 = [convert]::ToBase64String((Get-Content $pathToImage -Raw -AsByteStream))
Write-Output $base64
@pr0toc01
Copy link

You might consider adding the switch -Raw for better performance

Powershell 5.1
[String]$base64 = [convert]::ToBase64String((Get-Content $transactionImage.FullName -Raw -Encoding Byte))

Powershell 6+
[String]$base64 = [convert]::ToBase64String((Get-Content $pathToImage -Raw -AsByteStream))

@pferreirafabricio
Copy link
Author

@pr0toc01 Thank you for pointing this out! The gist was updated!

Performance comparison

I used this script to measure: Time.ps1

Powershell Core (6+)

Without -Raw flag:

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 1
Milliseconds      : 262
Ticks             : 12621640
TotalDays         : 1.46083796296296E-05
TotalHours        : 0.000350601111111111
TotalMinutes      : 0.0210360666666667
TotalSeconds      : 1.262164
TotalMilliseconds : 1262.164

With -Raw flag:

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 22
Ticks             : 227180
TotalDays         : 2.62939814814815E-07
TotalHours        : 6.31055555555556E-06
TotalMinutes      : 0.000378633333333333
TotalSeconds      : 0.022718
TotalMilliseconds : 22.718

Powershell Windows

Without -Raw flag:

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 1
Milliseconds      : 502
Ticks             : 15026649
TotalDays         : 1.73919548611111E-05
TotalHours        : 0.000417406916666667
TotalMinutes      : 0.025044415
TotalSeconds      : 1.5026649
TotalMilliseconds : 1502.6649

With -Raw flag:

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 36
Ticks             : 363624
TotalDays         : 4.20861111111111E-07
TotalHours        : 1.01006666666667E-05
TotalMinutes      : 0.00060604
TotalSeconds      : 0.0363624
TotalMilliseconds : 36.3624

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment