Reputation: 21
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.
NOTE: IT HAS to be powershell...
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..
This is what I have so far:
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
EDIT:
I found a way to convert the source into an image using the following 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)
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.
MemoryStream = New-Object System.IO.MemoryStream
$bitmap.save($MemoryStream)
$Bytes = $MemoryStream.ToArray()
$MemoryStream.Flush()
$MemoryStream.Dispose()
$iconB64 = [convert]::ToBase64String($Bytes)
Upvotes: 0
Views: 1606
Reputation: 21
$bitmap | gm definition shows that a second parameter of imageformat is required.
Try adding an imageformat to the bitmapsave. This seems to work for me:
MemoryStream = New-Object System.IO.MemoryStream
$bitmap.save($MemoryStream, [System.Drawing.Imaging.ImageFormat]::Jpeg)
$Bytes = $MemoryStream.ToArray()
$MemoryStream.Flush()
$MemoryStream.Dispose()
$iconB64 = [convert]::ToBase64String($Bytes)
Upvotes: 2
Reputation: 9
Maybe I'm misunderstanding the problem here, but converting images to Base64 should be as simple as this:
[convert]::ToBase64String((Get-Content $ImagePath -Encoding Byte))
Again, I might have misunderstood your issue, but I have used that to imbed blobs in GUIs so that I don't have any file dependencies.
Upvotes: 0