“'null'的值对流无效”

时间:2015-09-24 07:02:53

标签: image powershell memory getresponsestream

尝试将图像从URL下载到内存中。在响应流上出错。

使用“1”参数调用“FromStream”的异常:“'null'的值对'stream'无效。”

Function Download-Image {
$req = [System.Net.WebRequest]::Create
("http://www.wired.com/images_blogs/business/2012/12/google.jpg")
    $response = $req.GetResponse()
    $ResponseStream = $Response.GetResponseStream()
    [System.IO.Stream]$stream = $ResponseStream
    #$response.close()
}

[byte[]]$image = Download-Image

Add-Type -AssemblyName System.Windows.Forms

$img = [System.Drawing.Image]::FromStream([System.IO.MemoryStream]$image)
[System.Windows.Forms.Application]::EnableVisualStyles()
$pictureBox = new-object Windows.Forms.PictureBox
$pictureBox.Width =  $img.Width
$pictureBox.Height =  $img.Height
$pictureBox.Image = $img

$form = new-object Windows.Forms.Form
$form.Width = $img.Width
$form.Height =  $img.Height
$form.AutoSize = $True
$form.AutoSizeMode = "GrowAndShrink"
$form.Icon = $icon
$form.controls.add($pictureBox)
$form.Add_Shown( { $form.Activate() } )
$form.ShowDialog()

1 个答案:

答案 0 :(得分:0)

您需要在赋值后从函数返回值:

Function Download-Image {
$req = [System.Net.WebRequest]::Create
("http://www.wired.com/images_blogs/business/2012/12/google.jpg")
    $response = $req.GetResponse()
    $ResponseStream = $Response.GetResponseStream()
    [System.IO.Stream]$stream = $ResponseStream
    #$response.close()
    $req
}

在你的情况下,$ image变量的值为$ null:

[byte[]]$image = Download-Image

<强>更新

要将图像作为字节数组下载,您可以使用this post中的解决方案:

var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");