2014-11-08 87 views
1

我想捕獲一個web圖像到一個變量進行處理(見下文)。我想避免將它保存到文件,處理文件,然後刪除文件。如圖所示,我可以將網絡請求輸出直接保存到文件中,但如果將輸出保存到變量中,則將變量內容保存到文件中,但結果不同。Powershell,使用outvariable保存web圖像

# saving output to a file works 
     $image='https://www.google.com/images/srpr/logo11w.png' 
     Invoke-WebRequest $image -outfile image1.png 

    <# I want to skip creating a file, using it, then deleting it 
    Save the image into a variable, convert to base64 to store in db, retrieve from db, convert back, save to a file 
    #> 
     Invoke-WebRequest $image -OutVariable imagevariable 
     $imagevariable | out-file image2.png # this is not a valid image 

    # Convert to base64 (using PSCX add-on) to store string 
     $toBase64=ConvertTo-Base64($imagevariable) 

    # save to, retrieve from db 
     #Invoke-Sqlcmd insert... 
     #Invoke-Sqlcmd select... 

    # Convert from base64 (using PSCX add-on) & output to a file 
     $fromBase64 | ConvertFrom-Base64 -OutputPath image3.png 

爲了方便起見,我將使用PSCX community extensions進行base64轉換。

回答

2

你真的很接近,但圖像字節在返回的對象的Content屬性,試試這個:

$toBase64 = $imagevariable.Content | ConvertTo-Base64 
+0

KH,使用你的建議,我希望這樣的: 調用-的WebRequest $圖像-OutVariable imagevariable $ imagevariable.content | out-file image2.png創建一個好的png,但它不是。 – Albert 2014-11-13 15:34:17

+0

這是因爲Out-File使用Unicode的默認編碼,並且意味着輸出文本而不是字節。用這個代替'|設置內容image2.png -Enc Byte' – 2014-11-13 18:13:04

+0

'Invoke-WebRequest $ image -OutVariable imagevariable $ imagevariable.content | set-content image2.png -enc byte'是解決方案。謝謝基思。如果您可以再花點時間,我會很感激,如果您可以用技術參考進行註釋,如果您知道一個,因爲我找不到任何東西。 – Albert 2014-11-13 22:32:08