1

Attempting to download an image from a URL into memory. Getting an error on the response stream.

Exception calling "FromStream" with "1" argument(s): "Value of 'null' is not valid for '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 Answers1

0

You need to return value from function after assignment:

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
}

In your case $image variable just have a value of $null:

[byte[]]$image = Download-Image

Updated:

To download image as byte array you can use solution from this post:

var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData("http://www.google.com/images/logos/ps_logo2.png");
Community
  • 1
  • 1
Mikhail Tumashenko
  • 1,683
  • 2
  • 21
  • 28
  • Ahh. Thanks. Added a return value for $stream, but seems now I need help converting a connectsream to a byte array. – user3638757 Sep 24 '15 at 07:37
  • Cannot convert the "System.Net.ConnectStream" value of type "System.Net.ConnectStream" to type "System.Byte[]". – user3638757 Sep 24 '15 at 07:39