I am trying to get an thumbnail image from the Microsoft Computer Vision Get Thumbnail API and save the response as a base64 encoded string that can be used in an html img tag like so:
<img src="data:image/gif;base64,...base64string..."></img>
If I start from a test.jpeg image I have on my local drive, I am able to generate a usable base64string:
[convert]::ToBase64String((get-content 'c:\test\test.jpeg' -encoding byte)) >> b64str.txt
When I try with data returned from the REST API I don't get get a usable base64string (I do get a string but it is not usable in the html img tag):
$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
I've been working on this for some days, and the above is as close as I have gotten to a string that looks close. The issue seems to be the format returned from the API service and the subsequent conversion to bytes and then base64string but I'm lost as to where to go from here.
CodePudding user response:
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.