簡體   English   中英

如何從 Azure Function 返回 base64 圖像作為二進制數據

[英]How to return base64 image from Azure Function as binary data

Azure Function HTTP 綁定從 Azure Blob 存儲讀取圖像作為 Base64 字符串。

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQTEhIUEhIUFBUV…K9rk8hCAEkjFMUYiEAI+nHIpsQh0AkisDYRTOiCAbWVtgCtI6IlkHh7LDTQXLH0EIQBj//2Q==

它使用新的緩沖區對其進行轉換:

const buf = new Buffer(pictureObj.data.split(",")[1], "base64");

然后它以這種方式返回這個緩沖區:

context.bindings.res = {
    "status": 200,
    "headers": {
        "Content-Type": type || "image/jpeg"
     },
     "body": new Uint8Array(buf)
};

不幸的是,這不起作用。 設置“isRaw”也不起作用,也無法返回緩沖區 (buf) 本身。 錯誤為 406(不可接受),正文為空。

問題是:如何通過 HTTP 輸出綁定返回 base64 作為二進制圖像?

此外,再添加一個 header(例如 Content-Length)失敗並出現此錯誤:

info: Worker.Node.2a68d094-3858-406b-a0c5-a81497b3436b[0]
  Worker 2a68d094-3858-406b-a0c5-a81497b3436b malformed message invocationResponse.outputData.data.http.headers: string{k:string} expected
[03/12/2017 02:44:32] A ScriptHost error has occurred
[03/12/2017 02:44:32] Error: Choose either to return a promise or call 'done'.  Do not use both in your script.
[03/12/2017 02:44:32] Error: Choose either to return a promise or call 'done'.  Do not use both in your script.

如果您使用的是Azure函數beta,則此方法應該有效:

context.res.setHeader("Content-Type", "image/jpeg")
context.res.raw(new Uint8Array(buf))

同樣,在使用raw或send時,不需要調用context.done,因為它被隱式調用。

多年來,context.res object 的語法發生了變化。 這是我最近用 TypeScript Azure Function 實現的方法。

    const base64Image: string = 'data:image/png;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxQTEhIUEhIUFBUV…K9rk8hCAEkjFMUYiEAI+nHIpsQh0AkisDYRTOiCAbWVtgCtI6IlkHh7LDTQXLH0EIQBj//2Q==';
const buffer: Buffer = new Buffer(base64Image.split(",")[1], "base64");

context.res = {
    headers: {
        "Content-Type": "image/png"
    },
    isRaw: true,
    // status: 200, /* Defaults to 200 */
    body: new Uint8Array(buffer)
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM