1

尝试将图像从 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()
4

1 回答 1

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

更新:

要将图像下载为字节数组,您可以使用这篇文章中的解决方案:

var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");
于 2015-09-24T07:21:49.580 回答