Base64 Encoding of Images via Powershell

Sunday, Nov 7, 2010 2 minute read Tags: powershell
Hey, thanks for the interest in this post, but just letting you know that it is over 2 years old, so the content in here may not be accurate.

Recently I was doing some CSS for a client but there was a bit of a problem with putting stuff into source control, basically there was a release coming up from one section of the source tree that I needed to put some images into for the CSS, but because they weren’t approved for this release I couldn’t commit them.

The new CSS wasn’t going to be included in this release either, but I wanted to get at least some stuff source controlled (it’s in a different part of the tree so I could commit it) and to achieve this with the images I decided to use base64 encoding.

If you’re not aware something that modern browsers (like IE8+, FF, Chrome, etc) are starting to support is RFC 2397 which is also known as the “data” URI scheme. The basic premise behind this (if you’re not interested in reading the whole spec yourself :P) is to allow you to embed an encoded version of a URI response in place of the URI itself. This allows you to do funky stuff like this:


This technique can also be used with CSS, in background images, and it’s what I decided to go with. But how do you convert an image to a base64 string? There’s plenty of helper sites on the web, or maybe you can write a C# console application to do it.

I decided to go a bit different with it, since it was something I’d be doing a few times I wanted it to be quite to write and easy to run, so Powershell was what I decided to go with.

So I hit up Jason Stangroome for some Powershell wizardry (read: he told me what to code) and came up with a nifty 2-line Powershell file:

[convert]::ToBase64String((get-content $path -encoding byte))

You then use it like so:

PS> .\ImageToBase64.ps1 C:\Path\To\Image.png >> base64.txt

Jason thinks you can do it with only a single line script by putting the Param declaration on the same line of convert statement, but I think that having it on 2 lines should be fine :P.