我需要将$ var转换为字节数组,以将其推送到[convert]::ToBase64String($var)
以便上传到sql DB。全部不使用Get-Content -file -encoding Byte,因为此脚本在Azure中运行,无法访问任何文件系统。
header 包含Auuth承载 token 。
$var = (invoke-restmethod -uri ...800x800.png -method -get -headers $head)
数据流如下所示:
PNG
IHDRÛphgAMA±ücHRM z&úèu0ê`:pºQ
...
[System.Array]$myarray = (invoke-restmethod...
$bytes = [System.Text.Encoding]::UTF8.GetBytes($myarray)
$encoded_array = [System.Convert]::ToBase64String($bytes)
在对base64字符串进行解码时,它被感知为应用程序/八位位组,而不是图像八位位组,并被破坏。
但是,照常运行
invoke-restmethod ... ... -outfile c:\test.png
[System.Convert]::ToBase64String (get-content c\test.png -encoding byte)
可以正常工作。
复制:
(invoke-restmethod -uri "URI to .png" -method -get )
然后使用它,直到将其转换为编码的base 64字符串为止。
所需结果是作为图像的base64字符串。
当前结果是一个以64为基数的字符串???并且没有被解码成任何有用的东西。
最佳答案
您可以使用以下代码将图像转换为base64:
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
然后转到此link,您可以成功将byte64转换为图像。
关于powershell - 在不使用Get-content的情况下将变量转换为字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58332279/