进程块在Graphics.DrawString中不起作用

时间:2018-04-03 00:17:25

标签: windows powershell object graphics

我有一个PowerShell函数(out())。当我想从管道将结果导入image时,它将从管道中获取最后一个对象。例如:我想在(gps)中显示所有对象:

function out {
[cmdletbinding()]
param(
    [parameter(
        Mandatory = $true,
        ValueFromPipeline = $true,
        ValueFromPipelineByPropertyName = $true)]
    [string[]]
    $n
)



    Process {
    $dirname = Get-Location | Select-Object -ExpandProperty Path
    $filename = $(Get-Date -f "yyyy-mm-dd--hh-mm-ss-tt") + "--image.png"
    $ImagePath = $dirname + "\" + $filename

      ForEach ($input in $n) {

        #PUT Your Image:
         $basefilename = "D:\ZalansDB\imgs\main\bg_D.jpg"
            $bmp = [System.Drawing.Bitmap]::FromFile("$basefilename")

            $font = new-object System.Drawing.Font ('Microsoft Sans Serif',16)
            $fcolors = [System.Drawing.Brushes]
            $graphics = [System.Drawing.Graphics]::FromImage($bmp)

            $graphics.DrawString($input,$font,$fcolors::White,30,40)


            $filename = $ImagePath
            $graphics.Dispose() 
            $bmp.Save($filename)
         } 




            Invoke-Item $filename 


    } 



}

Get-Process | Select-Object -First 2 | out

结果
enter image description here

我想在我的图像中显示前2个prcoess对象

1 个答案:

答案 0 :(得分:2)

我可以看到大量有效的方法。使用begin块来设置不会更改的变量。使用process块来收集进程名称。最后,使用end显示图像。我们使用-join将它们全部放在一个字符串中,这样我们就不必一直重绘和管理位置。

function Set-ProcessPicture{
    [cmdletbinding()]
    param(
        [parameter(
            Mandatory = $true,
            ValueFromPipeline = $true,
            ValueFromPipelineByPropertyName = $true)]
        [Alias("ProcessName")]
        $Process,
        [parameter(Mandatory=$false)]
        $BaseImagePath = "d:\temp\test.jpg"
    )


    begin{
        $dirname = Get-Location | Select-Object -ExpandProperty Path
        $font = new-object System.Drawing.Font ('Microsoft Sans Serif',16)
        $fcolors = [System.Drawing.Brushes]
        $baseBitmap = [System.Drawing.Bitmap]::FromFile($BaseImagePath)
        $graphics = [System.Drawing.Graphics]::FromImage($baseBitmap)

        $outputString = @()
    }

    Process {
        $outputString += $process
    } 
    end {
        $graphics.DrawString(($outputString -join "`r`n"),$font,$fcolors::White,30,40)
        $filename = [io.path]::Combine((Get-Location).Path,(Get-Date -f "yyyy-MM-dd--hh-mm-ss-fff") + "--image.png")
        $graphics.Dispose() 
        $baseBitmap.Save($filename)

        Invoke-Item $filename 
    }

}

Get-Process | Select-Object -First 2 | Set-ProcessPicture

Sample Output

我做了一些最佳实践代码更改。这不是我将如何离开它,但纠正你所遇到的问题。

注意:在格式字符串中使用MM数月