0

我正在尝试从 Microsoft Computer Vision Get Thumbnail API 获取缩略图,并将响应保存为 base64 编码的字符串,可以在 html img 标签中使用,如下所示:

<img src="data:image/gif;base64,...base64string..."></img>

如果我从本地驱动器上的 test.jpeg 图像开始,我可以生成可用的 base64string:

[convert]::ToBase64String((get-content 'c:\test\test.jpeg' -encoding byte)) >> b64str.txt

当我尝试使用从 REST API 返回的数据时,我没有得到可用的 base64string(我得到了一个字符串,但它在 html img 标签中不可用):

$acs_req_headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$acs_req_headers.Add("Ocp-Apim-Subscription-Key", "...subscriptionkey...")
$acs_req_body = '{"url":"https://...url.../test/test.jpg"}'
                
[convert]::ToBase64String(([System.Text.Encoding]::UTF8.GetBytes((Invoke-RestMethod 'https://...url...cognitiveservices.azure.com/vision/v3.2/generateThumbnail?width=100&height=100&smartCropping=true&model-version=latest' -Method 'POST' -Headers $acs_req_headers -Body $acs_req_body -ContentType 'application/json')))) >> b64str.txt

我已经为此工作了几天,上面的内容与我得到的看起来很接近的字符串一样接近。问题似乎是从 API 服务返回的格式以及随后转换为字节,然后是 base64string,但我不知道从这里去哪里。

4

1 回答 1

0

I tried to get an image from google images with Invoke-RestRequest and I didn't manage to convert it to a valid base64 string.

But, with Invoke-WebRequest I managed to do so because the content is already in byte format:

$req = Invoke-WebRequest -Method Get -Uri 'https://static.remove.bg/remove-bg-web/8fb1a6ef22fefc0b0866661b4c9b922515be4ae9/assets/start_remove-c851bdf8d3127a24e2d137a55b1b427378cd17385b01aec6e59d5d4b5f39d2ec.png'

$b64str = [convert]::ToBase64String($req.Content)

I saw from here that RestRequest does some conversion under the hood? Maybe that's what causing the issues.

Give Invoke-WebRequest a shot. But don't use it as Invoke-RestRequest because it returns a WebResponseObject object which contains a Content property where your actual response will be.

于 2021-09-22T11:53:15.513 回答