docx中图片浅色

<#
.SYNOPSIS
通过Word自动化调整docx中所有图片的亮度和对比度至40%
.DESCRIPTION
直接调用Word COM接口,无需依赖外部工具
.PARAMETER InputPath
输入docx文件路径
.PARAMETER OutputPath
输出处理后的docx文件路径(可与输入路径相同,覆盖原文件)
.\backcolor.ps1 -InputPath "C:\test\input.docx" -OutputPath "C:\test\output.docx"
#>

param(
    [Parameter(Mandatory=$true)]
    [string]$InputPath,
    [Parameter(Mandatory=$true)]
    [string]$OutputPath
)

# 检查输入文件是否存在
if (-not (Test-Path $InputPath -PathType Leaf)) {
    Write-Error "输入文件不存在:$InputPath"
    exit 1
}

# 创建Word应用实例
$word = New-Object -ComObject Word.Application
$word.Visible = $false  # 后台运行,不显示界面

try {
    # 打开文档
    $doc = $word.Documents.Open((Resolve-Path $InputPath).Path)

    # 处理嵌入式图片(InlineShape)
    foreach ($inlineShape in $doc.InlineShapes) {
        # 仅处理图片类型(排除图表、公式等)
        if ($inlineShape.Type -eq 3){  # 3 = wdInlineShapePicture
            $inlineShape.PictureFormat.IncrementBrightness(0.2)  # 亮度40%
            $inlineShape.PictureFormat.IncrementContrast(0.2)    # 对比度40%
            #Write-Host "已处理嵌入式图片(EditID: $($inlineShape.EditID))"
        }
    }


    # 保存处理后的文档
    $doc.SaveAs2((Resolve-Path (Split-Path $OutputPath -Parent)).Path + "\" + (Split-Path $OutputPath -Leaf))
    Write-Host "处理完成,输出文件:$OutputPath"
}
catch {
    Write-Error "处理失败:$_"
}
finally {
    # 关闭文档和Word实例,释放资源
    if ($doc) {
        $doc.Close()
        [System.Runtime.Interopservices.Marshal]::ReleaseComObject($doc) | Out-Null
    }
    if ($word) {
        $word.Quit()
        [System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
    }
    # 强制垃圾回收,避免残留进程
    [System.GC]::Collect()
    [System.GC]::WaitForPendingFinalizers()
}

  

posted @ 2025-08-11 09:18  Ender.Lu  阅读(9)  评论(0)    收藏  举报