Use base64 for Images in WPF-based PowerShell Forms

I’m currently building a notification module to let me know when VMware vCenter alerts go off in my home lab. I plan to share it, and wanted to use a non-standard icon, but didn’t want to require a separate download. I knew base64 would be the answer, and ultimately, some C# code from StackExchange helped me figure out what needed to be done.

Here’s what it looks like in my application. Note the image being used in both the popup and the notifyicon itself:


Below is the simplified code I used to display the icon within my application popup. The code contains comments that explains each step. It’s pretty straightforward: a quick conversion, then setting the image source to the converted stream.

# Add required assembly
Add-Type -AssemblyName PresentationFramework

# Setup the XAML
[xml]$script:xaml = '<Window 
        Title="base64 image demo" Height="200" Width="200" Background="Black">
        <Image Name="thisistheimage" Height="32" Width="32"/>

# Create the form and set variables
$script:form = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader $xaml))
$xaml.SelectNodes("//*[@Name]") | ForEach-Object { Set-Variable -Name ($_.Name) -Value $form.FindName($_.Name) -Scope Script }

# here's the base64 string

# Create a streaming image by streaming the base64 string to a bitmap streamsource
$bitmap = New-Object System.Windows.Media.Imaging.BitmapImage
$bitmap.StreamSource = [System.IO.MemoryStream][System.Convert]::FromBase64String($base64)

# Freeze() prevents memory leaks.

# Set source here. Take note in the XAML as to where the variable name was taken.
$thisistheimage.source = $bitmap

# Show form
$form.ShowDialog() | Out-Null

Working with PowerShell and WPF makes me realize that *this* is what I always wanted coding to be. Simplified yet powerful!

Chrissy is a Cloud and Datacenter Management & Data Platform MVP who has worked in IT for over 20 years. She is the creator of the popular SQL PowerShell module dbatools, holds a master's degree in Systems Engineering and is coauthor of Learn dbatools in a Month of Lunches. Chrissy is certified in SQL Server, Linux, SharePoint and network security. You can follow her on Twitter at @cl.

Posted in PowerShell, WPF