首页 > 解决方案 > 如何将图像转换为 Base64 字符串,并转换回图像,保存到 azure blob

问题描述

希望我正确地描述了这一点,并且可能非常简单

尝试将图像作为 base64 字符串在 json 有效负载中传递给用 Powershell 编写的 azure 函数,同时旨在将其最终作为结构化 azure blob 存储中的图像。

将本地文件编码为 Base64:

$content = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes([System.IO.File]::ReadAllText("$fileName")))
        

打包、发送和接收 json 有效负载没有问题。

在 Azure 函数中,http 触发

解码base64

$image = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($base64Content))
        

从那里,输出到blob:

Push-OutputBinding -Name outputBlob -Value $ImageBytes

输出的标准绑定:

{
   "name": "outputBlob",
   "path": "container/{filename}",
   "connection": "connectionName",
   "direction": "out",
   "type": "blob"
}

假设它是解码,则生成的 blob 不是图像。

提前致谢..

标签: azurepowershellbase64blob

解决方案


关于这个问题,请参考以下代码

功能码

using namespace System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."

$image=$Request.Body.Image

#read base64 image as bytes
$imageBytes=[System.Convert]::FromBase64String($image)

Push-OutputBinding -Name outputBlob -Value  $imageBytes

输出的标准绑定:

{
   "name": "outputBlob",
   "path": "outcontainer/{filename}",
   "connection": "connectionName",
   "direction": "out",
   "type": "blob"
}

用于发送请求的脚本

$fileName="faces.jpg"
$content=Get-Content -Path $fileName -Encoding Byte
$image=[System.Convert]::ToBase64String($content)

$body= @{"fileName"=$fileName;"image"=$image}|convertto-json

Invoke-WebRequest -Method Post -Uri "<url>" -Body $body -ContentType "application/json" -UseBasicParsing

在此处输入图像描述 在此处输入图像描述


推荐阅读