« Response to the Response | Main | Monad Tidbits »
August 08, 2005
More Monad Image Manipulation
Following up on my previous script that would rotate images and save them in a file with "rot." prepended to the name, here are two more similar ones.The first one scales images down by 50%, and saves them in a file with "_scale" appended to the name (before the file extension). The basic structure is similar to the earlier one:
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") | out-null
foreach ($f in resolve-path *) {
trap [OutOfMemoryException] {
write-host "Error processing" $f
continue
}
. {
$img = [System.Drawing.Image]::FromFile($f)
$format = $img.RawFormat
$bmp = new-object System.Drawing.Bitmap ([int]($img.width/2)),([int]($img.height/2))
$g = [System.Drawing.Graphics]::FromImage($bmp)
$g.InterpolationMode = [System.Drawing.Drawing2D.InterpolationMode]"HighQualityBicubic"
$g.ScaleTransform(0.5,0.5)
$g.DrawImage($img,$(new-object System.Drawing.Point 0,0))
$fi = get-childitem $f
$fn = $fi.FullName
$ex = $fi.extension
$newname = $fn.Substring(0,$fn.Length-$ex.Length) + "_scale" + $ex
$bmp.Save($newname,$format)
}
}
(I think technically I should call the Dispose() method on my Image, Bitmap, and Graphics objects, but for the sake of brevity I removed that).
Then this one watermarks pictures, overwriting the word "Adam" in 30% transparent gray text. For variety, it saves the new images with the same name but in a subdirectory called "watermark":
[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") | out-null
if (!$(test-path "./watermark")) {
new-item -type directory "./watermark" | out-null
}
foreach ($f in resolve-path *) {
trap [OutOfMemoryException] {
write-host "Error processing" $f
continue
}
. {
$img = [System.Drawing.Image]::FromFile($f)
$format = $img.RawFormat
$bmp = new-object System.Drawing.Bitmap $img.width,$img.height
$g = [System.Drawing.Graphics]::FromImage($bmp)
$g.DrawImage($img,$(new-object System.Drawing.Point 0,0))
$color = [System.Drawing.Color]::FromArgb(30,[System.Drawing.Color]"Gray")
$brush = new-object System.Drawing.SolidBrush $color
$font = new-object System.Drawing.Font "Arial",([int]($img.height/3))
$point = new-object System.Drawing.PointF ([int]($img.width/2)),([int]($img.height/3))
$sf = new-object System.Drawing.StringFormat
$sf.Alignment = [System.Drawing.StringAlignment]"Center"
$g.DrawString("Adam",$font,$brush,$point,$sf)
$fi = get-childitem $f
$newname = combine-path ($fi.DirectoryName) "watermark"
$newname = combine-path $newname $fi.Name
$bmp.Save($newname,$format)
}
}
The Graphics class has all kinds of functions you can use to draw on your images; this is just an example of two of them.
Posted by AdamBa at August 8, 2005 12:05 PM
Trackback Pings
TrackBack URL for this entry:
http://proudlyserving.com/cgi-bin/mt-tb.cgi/289