我需要将文件夹和子文件夹中的所有图片转换为jpg。我需要用命令文件批处理这个过程。 GUI工具针对我来说我需要脚本。
我尝试使用来自ImageMagick的mogrify.exe,还有convert.exe函数,但是afaik都可以转换图像。
我写了下一个剧本:
$rootdir = "E:\Apps\скрипты\temp1\graphics"
$files = dir -r -i *.png $rootdir
foreach ($file in $files) {.\mogrify.exe -format png *jpg $file}
但这不起作用,当我尝试运行它时,我遇到了错误:
mogrify.exe: unable to open file `*jpg' @ error/png.c/ReadPNGImage/3633.
mogrify.exe: Improper image header `E:\Apps\скрипты\temp1\graphics\telluric\day\
Athens\2011-07-03-17.png' @ error/png.c/ReadPNGImage/3641.
mogrify.exe: unable to open image `*jpg': Invalid argument @ error/blob.c/OpenBl
ob/2588.
我也找到下一个代码:
[Reflection.Assembly]::LoadWithPartialName('System.Drawing')
$img=[Drawing.Image]::FromFile("$(cd)\Max.jpg")
$img.Save("$(cd)\max.gif", 'Gif')
$img.Dispose()
我怎样才能让它与dirs树一起工作并将png和tiff转换为jpg?
答案 0 :(得分:15)
我已经做了类似的事情,将位图文件转换为图标文件:
http://sev17.com/2011/07/creating-icons-files/
我根据您的要求调整了它并测试了将图像文件转换为jpg的功能:
function ConvertTo-Jpg
{
[cmdletbinding()]
param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] $Path)
process{
if ($Path -is [string])
{ $Path = get-childitem $Path }
$Path | foreach {
$image = [System.Drawing.Image]::FromFile($($_.FullName));
$FilePath = [IO.Path]::ChangeExtension($_.FullName, '.jpg');
$image.Save($FilePath, [System.Drawing.Imaging.ImageFormat]::Jpeg);
$image.Dispose();
}
}
}
#Use function:
#Cd to directory w/ png files
cd .\bin\pngTest
#Run ConvertTo-Jpg function
Get-ChildItem *.png | ConvertTo-Jpg
答案 1 :(得分:0)
我改编了Chad Miller's answer,以便在此博文中添加设置JPEG质量等级的功能:
Benoît Patra's blog: Resize image and preserve ratio with Powershell
# Try uncommenting the following line if you receive errors about a missing assembly
# [void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
function ConvertTo-Jpg
{
[cmdletbinding()]
param([Parameter(Mandatory=$true, ValueFromPipeline = $true)] $Path)
process{
$qualityEncoder = [System.Drawing.Imaging.Encoder]::Quality
$encoderParams = New-Object System.Drawing.Imaging.EncoderParameters(1)
# Set JPEG quality level here: 0 - 100 (inclusive bounds)
$encoderParams.Param[0] = New-Object System.Drawing.Imaging.EncoderParameter($qualityEncoder, 100)
$jpegCodecInfo = [System.Drawing.Imaging.ImageCodecInfo]::GetImageEncoders() | where {$_.MimeType -eq 'image/jpeg'}
if ($Path -is [string]) {
$Path = get-childitem $Path
}
$Path | foreach {
$image = [System.Drawing.Image]::FromFile($($_.FullName))
$filePath = "{0}\{1}.jpg" -f $($_.DirectoryName), $($_.BaseName)
$image.Save($filePath, $jpegCodecInfo, $encoderParams)
$image.Dispose()
}
}
}
#Use function:
# cd to directory with png files
cd .\bin\pngTest
#Run ConvertTo-Jpg function
Get-ChildItem *.png | ConvertTo-Jpg