Wednesday, April 13, 2011

Powershell Base64 Image Generator For Data URIs

Data URIs are gaining in popularity. There are websites that will generate the URI (like http://www.motobit.com/util/base64-decoder-encoder.asp), but requires the uploading of files to someone else server, corporate policies can make these unusable. I haven't seen one in Powershell, so I made one. The code is pretty basic.

You need to know what MIME type for the file, but they are pretty easy to discover. The most common ones I have used:
  • image/gif
  • image/x-icon
  • image/vnd.microsoft.icon
  • image/png
  • image/jpeg

#####
#
#	Base64.ps1
#		Converts a file to or from base 64
#
#	Useful for generating data protocol image addresses:
#	In CSS:
#		background: #ff url('data:image/gif;base64,<Base64String>')
#
#	In HTML:
#		<img src="data:image/gif;base64,<Base64String>" alt="X">
#
#	Usage (encode):
#		.\base64.ps1 favicon.ico favicon.b64 -encode
#
#	Usage (encode & copy to clipboard):
#		.\base64.ps1 favicon.ico -encode -SetClipboard
#
#	Usage (decode):
#		.\base64.ps1 favicon.b64 favicon.ico -decode
#
#
#####
param (
	[string] $source = $(Throw 'source: required parameter'),
	[string] $destination = "",
	[switch] $encode,
	[switch] $decode,
	[switch] $SetClipboard
)

function Main
{
	$file = Get-Item($source);
	if ($encode)
	{
		$bytes = get-content -encoding byte $file.Fullname
		$result = [System.Convert]::ToBase64String($bytes);
		if ($SetClipboard) {Set-Clipboard $result;}
		if ($destination.length -eq 0)
		{
			return $result;
		}
		else
		{
			set-content -encoding UTF8 -Path ".\$destination" -Value $result;
		}
	}
	elseif ($decode)
	{
		$bytes = get-content -encoding UTF8 $file.Fullname;
		[System.Convert]::FromBase64String($bytes) | set-content -encoding Byte -Path ".\$destination";
	}
	else
	{
		Write-Host("The encode or decode switch is required.");
	}
}

. Main

For more information on Data URIs, refer to RFC2397 or the Wiki page for the Data URI Scheme for examples on how to use them.

No comments: