title: Convert a BitmapSource into a BitmapImage (Or Base64) through Powershell
body: <p>I want to make a powershell script that takes file icons and converts them into base64. There is an API assembly that allows me to get the file icons (Not just associated, but image thumbnails and video thumbnails). Unfortunately the format that it is given in is a BitmapSource. I would like to know how I could convert the source into an image, or more precisely, convert it into base64 strictly through powershell.</p>
  
  <p>NOTE: IT HAS to be powershell... </p>
  
  <p>I tried doing a ton of research to find the answer, but everything is done in c# which makes it hard for me to convert c# into powershell..</p>
  
  <p>This is what I have so far:</p>
  
  <pre><code>Add-Type -Path ..\dll\Microsoft.WindowsAPICodePack.Shell.dll
  Add-Type -Path ..\dll\Microsoft.WindowsAPICodePack.dll
  
  Import-Module ..\dll\Microsoft.WindowsAPICodePack.dll
  Import-Module ..\dll\Microsoft.WindowsAPICodePack.Shell.dll
  
  [System.Windows.Media.Imaging.BitmapSource] $iconSrc = [Microsoft.WindowsAPICodePack.Shell.ShellFile]::FromFilePath('image I am converting').Thumbnail.BitmapSource
  </code></pre>
  
  <p>EDIT:</p>
  
  <p>I found a way to convert the source into an image using the following code:</p>
  
  <pre><code>[System.Windows.Media.Imaging.BitmapSource] $iconSrc =  [Microsoft.WindowsAPICodePack.Shell.ShellFile]::FromFilePath ('Image to convert path').Thumbnail.BitmapSource
  $MemoryStream = New-Object System.IO.MemoryStream
  $enc = New-Object System.Windows.Media.Imaging.BmpBitmapEncoder
  $enc.Frames.Add([System.Windows.Media.Imaging.BitmapFrame]::Create($iconSrc))
  $enc.Save($MemoryStream)
  $bitmap = New-Object System.Drawing.Bitmap($MemoryStream)
  </code></pre>
  
  <p>However, I also need to convert the image into base64 which I am having trouble doing. I am trying to save the image to a memory stream but it becomes null when I look at the bytes.</p>
  
  <pre><code>MemoryStream = New-Object System.IO.MemoryStream
  $bitmap.save($MemoryStream)
  $Bytes = $MemoryStream.ToArray()
  $MemoryStream.Flush()
  $MemoryStream.Dispose()
  $iconB64 = [convert]::ToBase64String($Bytes)
  </code></pre>