【问题标题】:Create new Response from base64 image data with Javascript使用 Javascript 从 base64 图像数据创建新的响应
【发布时间】:2020-07-30 12:08:35
【问题描述】:

我想伪造回复。我有 png 图像的 base64 字符串数据。现在我想做出回应,但它不起作用。

我的代码:

const data = "data:image/png;base64,iVBORw0KGgoAAAA...";
const res = new Response(data, {
      status: 200,
      statusText: "OK",
      headers: {
        "Content-Type": "image/png",
        "Content-Length": data.length
      },
    });

我做了一些研究,似乎base64 不能只传递给响应体。它需要转换为缓冲区或类似的东西。

可以像这样在 NodeJS 中完成 Buffer.from(data, 'base64')

但我的代码只在浏览器中。

有什么方法可以实现吗?

【问题讨论】:

    标签: javascript base64 png response


    【解决方案1】:

    base64 是一个编码字符串,要获得实际图像,您需要使用atob 将其转换为二进制数据。这是一个例子:

    const b64String = data.split(',')[1];
    var byteString = atob(b64String);
    var arrayBuffer = new ArrayBuffer(byteString.length);
    var intArray = new Uint8Array(arrayBuffer);
    for (var i = 0; i < byteString.length; i++) {
        intArray[i] = byteString.charCodeAt(i);
    }
    var imageBlob = new Blob([intArray], {type: 'image/png'});
    const res = new Response(imageBlob, {
      status: 200,
      statusText: "OK",
      headers: {
        "Content-Type": "image/png",
        "Content-Length": imageBlob.size
      },
    });
    

    【讨论】:

      猜你喜欢
      • 2016-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多