如何将png保存为jpg而不将文件保存在dir中



我正在使用FromFile从文件中获取图像,它在FromFile行上的png有以下错误:

异常调用"FromFile"用";1〃;自变量:";给定路径的不支持格式">

因此,我正试图将bmp转换为jpg(请参阅下面FromFile上方的转换行(,但我看到的所有示例(似乎可用(都在保存文件。我不想把文件保存在目录中。我只需要图像格式,所以FromFile可以像这个例子一样使用它。我看到了ConvertTo Jpeg,但我不认为这是一个标准的powershell模块,或者不知道如何安装它。

我看到了这个链接,但我认为这不会使图像保持FromFile所需的格式。

这是我的代码:

$imageFile2 = Get-ChildItem -Recurse -Path $ImageFullBasePath -Include @("*.bmp","*.jpg","*.png") | Where-Object {$_.Name -match "$($pictureName)"}  #$imageFile | Select-String -Pattern '$($pictureName)' -AllMatches

Write-Host $imageFile2
if($imageFile2.Exists)
{
if($imageFile2 -Match "png")
{
$imageFile2 | .ConvertTo-Jpeg #I don't think this will work with FromFile below
}
$image = [System.Drawing.Image]::FromFile($imageFile2)  step
}
else {
Write-Host "$($imageFile2) does not exist"
}

然后我把它放在excel中:

$xlsx = $result | Export-Excel -Path $outFilePath -WorksheetName $errCode -Autosize -AutoFilter -FreezeTopRow -BoldTopRow  -PassThru # -ClearSheet can't ClearSheet every time or it clears previous data  ###left off
$ws = $xlsx.Workbook.Worksheets[$errCode]
$ws.Dimension.Columns  #number of columns
$tempRowCount = $ws.Dimension.Rows     #number of rows
#only change width of 3rd column
$ws.Column(3).Width
$ws.Column(3).Width = 100
#Change all row heights
for ($row = 2 ;( $row -le $tempRowCount ); $row++)
{
#Write-Host $($ws.Dimension.Rows)
#Write-Host $($row)
$ws.Row($row).Height
$ws.Row($row).Height = 150
#place the image in spreadsheet
#https://github.com/dfinke/ImportExcel/issues/1041  https://github.com/dfinke/ImportExcel/issues/993
$drawingName = "$($row.PictureID)_Col3_$($row)" #Name_ColumnIndex_RowIndex   
Write-Host $image
$picture = $ws.Drawings.AddPicture("$drawingName",$image)
$picture.SetPosition($row - 1, 0, 3 - 1, 0)
if($ws.Row($row).Height -lt $image.Height * (375/500)) {
$ws.Row($row).Height = $image.Height * (375/500)
}
if($ws.Column(3).Width -lt $image.Width * (17/120)){
$ws.Column(3).Width = $image.Width * (17/120)
}
}

更新:

我只是想重申,FromFile不能用于png图像。所以Hey Scripting Guy这样保存图像的地方不起作用:

$image = [drawing.image]::FromFile($imageFile2)

我发现$imageFile2路径中有两个文件名。这两个文件必须符合Get-ChildItem/Where-Object/匹配条件。这些图像看起来完全相同,但名称相似,因此易于处理。在我拆分名称后,它会从文件中删除。

最新更新