Image Manipulation in PowerShell
The other week, I showed a Get-ProgID function that I used to help someone at Microsoft Research find a good object to talk to images. A few comments jumped to one of the possible solutions, which is to use the .NET Drawing assembly (which I have to load first). I wanted to be reasonably sure that the way to get at the image metadata was efficient and didn’t require loading up any assemblies PowerShell hadn’t loaded already. Looking at the output of Get-ProgID, Two COM objects jumped out at me:
These two COM objects are part of a whole fun family of scriptable COM objects that work with the Microsoft Windows Image Acquisition Layer. WIA has been in Windows since XP SP1, and it doesn’t just give me a cheap way to get at the width and height of my image, it gives me a way to crop, resize, overlay, and rotate my images too. Check out this page for a ton of examples of fun things you can do with WIA.
I gave the Microsoft Research friend the solution to the width and height problem last week. Supposing I had a file, try.jpg, in my current directory, here’s how I’d get at the width and the height of that file:
$image = New-Object -ComObject Wia.ImageFile $image.LoadFile("$pwd\try.jpg") $image.Width, $image.Height
I think this is pretty straightforward way to get at the image properties without having to load up new assemblies. Since I figured out that more cool scenarios were possible with the these COM objects, I couldn’t really resist writing a more complete image manipulation module in PowerShell.
So far, this library includes functions that help resize, crop, overlay, and rotate images. It also contains a function, Get-Image, which will take the output of Get-ChildItem and return all files WIA can load with nifty little script methods to crop and scale the current image. Each function has inline help and examples.
The module is attached to the post in a .ZIP file. Simply download and unzip the file into a directory called Image underneath $env:UserProfile\Documents\WindowsPowerShell\Modules and then run Import-Module Image. I hope you have as much fun with it as have.
Hope this helps,
James Brundage [MSFT]