将所有图像转换为jpg格式

8
我需要将文件夹和子文件夹中的所有图片转换为jpg格式。我需要用命令文件批处理此过程,GUI工具对我来说是无关紧要的,我需要脚本。
我尝试使用ImageMagick中的mogrify.exe,还有convert.exe功能,但据我所知,它们都能够转换图像。
我编写了下面的脚本:
$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()

我如何使其在目录树中运行,并将PNG和TIFF文件转换为JPG格式?

2个回答

19

我曾经在这里将位图文件转换成图标文件:

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

看起来不错;不过我会使用 [IO.Path]::ChangeExtension( $_.FullName, '.jpg' ) 而不是手动字符串格式化。 - Emperor XLII
ChangeExtension可以更改现有文件的扩展名。我不想更改原始文件。 - Chad Miller
ChangeExtension重新格式化路径字符串,使其指向具有不同扩展名的文件(该文件可能不存在)。它不会对文件进行任何操作。这就是为什么它在IO.Path而不是IO.File或IO.Directory命名空间中的原因。 - Ross Presser

1

我根据Chad Miller的回答进行了改编,以便从这篇博客文章中设置JPEG质量级别:
Benoît Patra的博客:使用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

如何解决从带有 Alpha 通道的 PNG 中获取反转颜色的问题? - Ross Presser
@RossPresser 我自己不知道,但是快速搜索得到了这个答案。请注意,System.Drawing.Image是纯.NET API,因此任何使用.NET(无论是C#还是PS)的答案都可以“翻译”。 - ComFreek
有趣。我最终只是将这42张图片复制到另一台机器上,以便我可以使用imagemagick。但我会记在心里,以备将来之需。 - Ross Presser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接