转换后的base64映像不起作用,如何获得真实的base64映像? [英] Converted base64 image does not work, how can I get true base64 image?

查看:93
本文介绍了转换后的base64映像不起作用,如何获得真实的base64映像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试将请求有效负载转换为base64,但是我的代码结果不是有效的base64映像.当我尝试在浏览器中使用它时,它不会显示图像.

I try to convert my request payload to base64 but the result of my code is not a valid base64 image. When I try to use it in the browser, it doesn't display the image.

所以我尝试编写简单的代码将图像转换为base64或使用npm模块,但是结果是相同的,并且我没有得到有效的图像!

So I try to write simple code to convert image to base64 or using npm modules but the result is the same and I don't get a valid image!

const request = require('request');

const url = "http://cdn1.giltcdn.com/images/share/uploads/0000/0001/7250/172502872/420x560.jpg";

request({url, gzip: true}, function (err, res, body) {

    if(!err){
        const data = "data:" + res.headers["content-type"] + ";base64," + Buffer.from(body, 'binary').toString('base64');
        console.log(data);
    }
});

server.get("/test", function(req, res){
    const data = "data:" + req.headers["content-type"] + ";base64," + Buffer.from(req.data.payload, 'binary').toString('base64');
    console.log(data);
});

结果是相同的(当我在浏览器中复制和粘贴时,它不显示图像):

The result is the same (when i copy and paste in browser, it doesn't display the image):

data:image/jpeg; base64,/f39/QAQSkZJRgABAQAAAQABAAD9/QBDAAEBA ...

data:image/jpeg;base64,/f39/QAQSkZJRgABAQAAAQABAAD9/QBDAAEBA...

当我将此 https://www.base64-image.de/网站用于转换为base64图像,结果是(当我在浏览器中复制并粘贴时,它可以工作并显示图像):

When i used this https://www.base64-image.de/ website for converting to base64 image, the result is (when i copy and paste in browser, it works and displays the image):

data:image/jpeg; base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBA ...

data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBA...

为什么结果不同?为什么缓冲缓冲到base64无效?

Why are the results different and why doesn't buffer to base64 work?

推荐答案

似乎您需要将encoding: null设置为request函数的选项,如

It seems like you need to set encoding: null as an option for the request function, as explained in this answer. It forces the body to be returned as binary instead of utf8 which is the default.

const request = require('request');

const url = "http://cdn1.giltcdn.com/images/share/uploads/0000/0001/7250/172502872/420x560.jpg";

request({url, gzip: true, encoding: null}, function (err, res, body) {
    if(!err) {
        const data = "data:" + res.headers["content-type"] + ";base64," + Buffer.from(body, 'binary').toString('base64');
        console.log(data);
    }
});

这篇关于转换后的base64映像不起作用,如何获得真实的base64映像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆