Image Conversion

PowerShell Team

 
I needed to convert some images from bmp to gif for a web site I’ve been working on.  I figured that I could script this pretty easy – here’s what I came up with.  It’s a little more general than I needed, and I thought it might be useful to others.  Anyway, it’s useful to me. 
 
 
# Convert one graphic image to another
param ( $inFile, $type = “gif”, $outFile, [switch]$force )
#
# First check to see if our input file exists
$iFile = (resolve-path $inFile -ea silentlycontinue ).path
if ( ! $iFile ) { “File ‘$inFile’ not found, exiting” ; exit }
 
# now check to see if the output file exists, if force
# we will continue, otherwise we exit
if ( ! $outFile )
{
    $tFile = get-item (resolve-path $inFile)
    $outFile = $tFile.Fullname -replace ($tFile.Extension + “`$”),”.$type”
}
if ( (test-path $outFile) -and (! $force) ) { “File ‘$outFile’ exists, exiting”; exit }
 
# make sure we have an encoder before changing anything on
# the filesystem
$codecs = [drawing.imaging.ImageCodecInfo]::GetImageEncoders() |
        foreach { $h = @{} } { $h.($_.formatdescription) = $_ } { $h }
$encoder = $codecs.$type
if ( ! $encoder ) 
{
        “No encoder of type ‘$type’, exiting”;
        “Available encodings are: ” + [string]::Join(“, “, $h.keys)
        exit
}
 
# This hoop is needed because resolve-path needs
# the file to actually exist.  We shouldn’t get here
# unless the file doesn’t exist, or we’re going to remove it
# by force.
if ( test-path $outFile ) { remove-item $outFile }
[void](new-item -type file $outFile)
$outFile = (resolve-path $outFile).path
remove-item $outFile
 
# read the image
$image = [system.drawing.image]::FromFile($iFile)
$image.Save($outFile, $encoder.FormatId)
$image.Dispose()
# Get the file we just created
get-item $outFile
 

0 comments

Discussion is closed.

Feedback usabilla icon