Skip to content

Instantly share code, notes, and snippets.

@eugrus
Created December 30, 2024 15:57
Show Gist options
  • Save eugrus/47ed8b139b56a86b953dcfcdf629fc90 to your computer and use it in GitHub Desktop.
Save eugrus/47ed8b139b56a86b953dcfcdf629fc90 to your computer and use it in GitHub Desktop.
View an image encoded in a Base64 line from clipboard
Add-Type -AssemblyName System.Drawing
function Test-Base64 {
param (
[string]$base64
)
try {
[Convert]::FromBase64String($base64)
return $true
} catch {
return $false
}
}
try {
$base64 = Get-Clipboard
# Clean up the base64 string
$base64 = $base64 -replace '^data:image\/\w+;base64,', '' # Remove data URL prefix
$base64 = $base64 -replace '\s+', '' # Remove all whitespace
$base64 = $base64 -replace '[^a-zA-Z0-9+/=]', '' # Keep only valid base64 chars
$base64 = $base64.PadRight([math]::Ceiling($base64.Length / 4) * 4, '=') # Pad the base64 string
if (-not (Test-Base64 $base64)) {
Write-Error "Invalid base64 string"
exit
}
$imageBytes = [Convert]::FromBase64String($base64)
$memoryStream = New-Object System.IO.MemoryStream($imageBytes, 0, $imageBytes.Length)
$bitmap = [System.Drawing.Bitmap]::FromStream($memoryStream)
# Create a GDI graphics object to display the image
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.DrawImage($bitmap, 0, 0)
# Display the image in a new window
$form = New-Object System.Windows.Forms.Form
$form.Text = "Base64 Image Viewer"
$form.Width = $bitmap.Width
$form.Height = $bitmap.Height
$form.BackgroundImage = $bitmap
$form.BackgroundImageLayout = 'None'
$form.ShowDialog()
}
catch {
Write-Error "Error: $_"
}
finally {
if ($memoryStream) { $memoryStream.Dispose() }
if ($bitmap) { $bitmap.Dispose() }
if ($graphics) { $graphics.Dispose() }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment