Created
November 23, 2018 18:22
-
-
Save brunolm/ceefbf4ee61da63fad5f004db96c5c82 to your computer and use it in GitHub Desktop.
Powershell: Get-ImageBase64 from FILE or URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Get-ImageBase64([string]$file) { | |
if ($file -like 'http*') { | |
return Get-ImageBase64FromUrl($file); | |
} | |
return Get-ImageBase64FromFile($file); | |
} | |
function Get-ImageBase64FromFile( | |
[string] | |
[ValidateScript( { Test-Path $_ })] | |
$file | |
) { | |
$type = Get-MimeType $file; | |
$base64 = [convert]::ToBase64String((Get-Content $file -Encoding byte)); | |
return "data:$type;base64,$base64"; | |
} | |
function Get-ImageBase64FromUrl([Uri]$url) { | |
$b = Invoke-WebRequest $url; | |
$type = $b.Headers["Content-Type"]; | |
$base64 = [convert]::ToBase64String($b.Content); | |
return "data:$type;base64,$base64"; | |
} | |
function Get-MimeType($CheckFile) { | |
Add-Type -AssemblyName "System.Web" | |
[System.IO.FileInfo]$checkFile = $CheckFile | |
$mime_type = '' | |
if ($checkFile.Exists) { | |
$mime_type = [System.Web.MimeMapping]::GetMimeMapping($checkFile.FullName); | |
} | |
return $mime_type; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment