美文网首页
node获取网络图片并转化为base64

node获取网络图片并转化为base64

作者: 2359634711 | 来源:发表于2019-03-23 20:03 被阅读0次
    var request = require('request');
    var fs = require('fs');
     
    var img_src = 'https://www.baidu.com/img/bd_logo1.png'; //获取图片的url
            //采用request模块,向服务器发起一次请求,获取图片资源
            request.head(img_src,function(err,res,body){
                if(err){
                    console.log(err);
                }
            });
             
    var img_filename = 'mu.jpg';  
        request(img_src).pipe(fs.createWriteStream('./'+ img_filename));     //通过流的方式,把图片写到本地/image目录下,并用新闻的标题和图片的标题作为图片的名称。
    

    读取网络图片并转换成base64,函数

                _initImg(){
                    var that = this;
                    this.imgSrc = ''
                    return new Promise((resolve) => {
                        request.get({
                            url: 'http://tyrz.gdbs.gov.cn/am/imageServlet?id=0.2950070475790554',
                            headers: {
                                'Host': 'tyrz.gdbs.gov.cn',
                                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36',
                                'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
                                'Referer': 'http://tyrz.gdbs.gov.cn/am/login/initAuth.do?gotoUrl=http%3A%2F%2Ftyrz.gdbs.gov.cn%2Fam%2Foauth2%2Fauthorize%3Fservice%3DinitService%26response_type%3Dcode%26client_id%3DgdbsYSS%26scope%3Dall%26client_secret%3D123qwer%26redirect_uri%3Dhttp%253A%252F%252Fwww.gdzwfw.gov.cn%252F_tif_sso_login_%252F%253Furl%253D%25252F_in_%25252F%25253Fr%25253D%2525252Fportal%2525252Fbranch-hall%2525253ForgCode%2525253D59071685X%2525252520%25252525E5%2525252595%25252525A5%25252525202019%2525252F3%2525252F23%252525252018%2525253A47%2525253A20%252526p%25253Dportal',
                            },
                            encoding: null
                        }, (err, res, body) => {
                           //console.log(Buffer.isBuffer(body))
                            var base = body.toString('base64')
                            resolve(base)
                        })
    
                    })
                }
    

    相关文章

      网友评论

          本文标题:node获取网络图片并转化为base64

          本文链接:https://www.haomeiwen.com/subject/sxhevqtx.html