简体   繁体   English

使用 Javascript 从 base64 图像数据创建新响应

[英]Create new Response from base64 image data with Javascript

I want to fake a response.我想假装回复。 I have the base64 string data of a png image.我有一个png图像的 base64 字符串数据。 Now I want to make a response but It does not work.现在我想做出回应,但它不起作用。

My code:我的代码:

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
      },
    });

I did some research, and it seems like base64 can not just be passed to response body.我做了一些研究,似乎base64不能只传递给响应体。 It needs to be converted to a buffer or something like that.它需要转换为缓冲区或类似的东西。

It can be done in NodeJS like this Buffer.from(data, 'base64')它可以像这样在 NodeJS 中完成Buffer.from(data, 'base64')

But my code is in the browser only.但我的代码只在浏览器中。

Is there any way that I can implement this.有什么方法可以实现这一点。

base64 is an encoded string, to get the actual image you need to convert it to binary data using atob . base64 是一个编码字符串,要获得您需要使用atob将其转换为二进制数据的实际图像。 here is an example:这是一个例子:

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
  },
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM