PowerShell中进行图像格式转换

挖坟是不太好的事情, 不过从PowerShell团队上看到下面的代码, 非常好. 这段代码是由: James W. Truher[MS] 编写. 将其存储成ps1文件.

执行:

PS C:/Documents and Settings/Administrator> ./Convert-Image.ps1 -inFile 01.jpg

GAC    Version        Location
---    -------        --------
True   v2.0.50727     C:/WINDOWS/assembly/GAC_MSIL/System.Drawing/2.0.0.0__b03f5f7f11d50a3a/System.Drawing.dll

LastWriteTime : 2008-7-25 22:05:36
Length        : 135580
Name          : 01.gif

 

代码如下:

# Convert one graphic image to another

param ( $inFile, $type = "gif", $outFile, [switch]$force )

[reflection.assembly]::LoadWithPartialName("System.drawing")

#

# 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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值