1

I need to convert the $var to a byte array to push it to [convert]::ToBase64String($var) for upload to a sql DB. All without using Get-Content -file -encoding Byte, as this script is running in Azure without access to any filesystem.

Header contains Auuth bearer token.

$var = (invoke-restmethod -uri ...800x800.png -method -get -headers $head)

Data stream looks like this:

PNG

IHDR Ûph gAMA ±üa cHRM z& ú è u0 ê` : pºQ< bKGD ÿ ÿ ÿ ½§ tIMEã 5Þ IDATxÚìý[°e[}ß?Æ\kgÌçä¹:UÝÕ¥Ôh!]@Rè ÆÌÕ°ÍÃ?øÁðà'¿áðG¶#ÆÆ1!ä ² ...

 [System.Array]$myarray = (invoke-restmethod...
 $bytes = [System.Text.Encoding]::UTF8.GetBytes($myarray)
 $encoded_array = [System.Convert]::ToBase64String($bytes)

Upon decoding of the base64 string, it is sensed as a application/octet instead of an image octet and is broken.

However, running the usual

invoke-restmethod ... ... -outfile c:\test.png
[System.Convert]::ToBase64String (get-content c\test.png -encoding byte)

works, as it should.

To reproduce:

(invoke-restmethod -uri "URI to .png" -method -get )

then play with it till you can get it into an encoded base 64 string.

Wanted result is a base64 string that is the image.
Current result is a base 64 string that is ??? and isn't decoded into anything useful.

  • Check this out : https://stackoverflow.com/questions/15414678/how-to-decode-a-base64-string , I am assuming you must be using the wrong encoder. – Mohit Verma Oct 11 '19 at 08:38

2 Answers2

2

You could use the following code to convert image to byte64:

1.

$file='C:\aaa.png'
$strm=([io.FileInfo]$file).OpenRead()
$bytes=New-Object byte[] $strm.Length
$strm.Read($bytes,0,$strm.Length)
$base64String=[convert]::ToBase64String($bytes)
$base64String

2.

$url='C:\aaa.png' or 'https://xxx/aaa.png'
$wc=New-Object System.Net.WebClient
$bytes=$wc.DownloadData($url)
$base64String1=[convert]::ToBase64String($bytes)
$base64String1

3.

$url='C:\aaa.png' or 'https://xxx/aaa.png'
$bytes = Invoke-WebRequest -Uri $url -Method Get | Select-Object -ExpandProperty Content
$base64String2=[convert]::ToBase64String($bytes)
$base64String2

Then go to this link you could successfully convert byte64 to image.

Joey Cai
  • 18,968
  • 1
  • 20
  • 30
  • Great code, i had found the 2nd answer independently. But now my question is: What exactly is the .net.WebClient and besides the obvious, how is it different than the invoke-restmethod? It almost seems that I should be using .net.webclient instead of Invoke-RestMethod to begin with. – Michael Curtis Oct 12 '19 at 22:36
0

I found my answer by using these commands:

$wc = New-Object System.Net.WebClient
$wc.Headers["Authorization"] = "Bearer <token>"
$bytes = $wc.DownloadData("URL")
$base64string = [Convert]::ToBase64String($bytes)