« DOS Ain't Done til Lotus Won't Run? | Main | Monad Webcasts »

August 03, 2005

Rotate Images With Monad

When mainpulating pictures I sometimes want to go through an entire directory and perform the same operation on every picture.

The following MSH script takes avantage of the .Net Image class to rotate each picture in a directory 90 degrees clockwise. It creates a new file with "rot." prepended to the name, in the same format as the original:

[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") | out-null

foreach ($f in resolve-path *) {
    trap [OutOfMemoryException] {
        write-host "Error processing" $f
    . {
        $img = [System.Drawing.Image]::FromFile($f)
        $format = $img.RawFormat
        $fi = get-childitem $f
        $newname = combine-path ($fi.DirectoryName) ("rot." + $fi.Name)

The LoadWithPartialName() loads in the .Net assembly with the classes we use; System.Drawing is not loaded into Monad by default (there is some debate about whether you should use LoadWithPartialName(), but I don't know a better way to load a known .Net assembly without locking it to a particular version).

The trap statement catches the OutOfMemoryException which is what FromFile() somewhat inexplicably throws if the file is not actually an image of some sort. The continue statement inside the trap means "continue execution at the next statement after the exception." In this case "next statement" means "next statement at the same scope level as the trap" which is why the entire block of code that we want the trap to guard is a dotted script block -- that makes the whole thing one statement from the point of view of the trap, so the "continue" inside the trap jumps to just after that statement, which is the end of the foreach block. The foreach will then interate again and the next file will be processed.

RotateFlip() takes an object of type System.Drawing.RotateFlipType. Looking at MSDN you can see that this enumeration allows you to any combination of rotation (in 90 degree increments) and X/Y/both flipping.

Posted by AdamBa at August 3, 2005 09:33 AM

Trackback Pings

TrackBack URL for this entry: