【发布时间】:2022-01-28 23:09:53
【问题描述】:
我正在使用 FromFile 从文件中获取图像,并且 FromFile 行上的 png 出现以下错误:
使用“1”参数调用“FromFile”的异常:“给定路径的 不支持格式。”
所以,我正在尝试将 bmp 转换为 jpg,(请参阅下面 FromFile 上方的转换行)但我看到的所有示例(似乎可用)都是 saving the file。我不想将文件保存在目录中。我只需要图像格式,因此 FromFile 可以像this example 一样使用它。看到了ConvertTo-Jpeg,但是我觉得这不是标准的powershell模块,或者不知道怎么安装。
我看到了this link,但我认为这不会使图像保持 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)
【问题讨论】:
-
您收到的错误与 图像格式 无关,而与您传递给
FromFile()的 路径 有关。改用$image = [drawing.image]::FromFile($imageFile2.FullName)
标签: image powershell export-to-excel bmp fromfile