nodejs抓取網絡圖片轉換爲base64編碼的圖片

抓取網絡圖片須要加載http模塊node

//假定這是index.js文件數組

var http = require('http');服務器

var url = 'http://p0.meituan.net/tuanpic/3df525af5a3f7fe04077567d2a6caf794904.png';  //一張網絡圖片網絡

 

http.get(url,function(res){
  var chunks = []; //用於保存網絡請求不斷加載傳輸的緩衝數據
  var size = 0;   //保存緩衝數據的總長度koa

  res.on('data',function(chunk){
    chunks.push(chunk);  //在進行網絡請求時,會不斷接收到數據(數據不是一次性獲取到的),ui

                //node會把接收到的數據片斷逐段的保存在緩衝區(Buffer),編碼

                //這些數據片斷會造成一個個緩衝對象(即Buffer對象),lua

                //而Buffer數據的拼接並不能像字符串那樣拼接(由於一箇中文字符佔三個字節),url

                //若是一個數據片斷攜帶着一箇中文的兩個字節,下一個數據片斷攜帶着最後一個字節,.net

                //直接字符串拼接會致使亂碼,爲避免亂碼,因此將獲得緩衝數據推入到chunks數組中,

                //利用下面的node.js內置的Buffer.concat()方法進行拼接

         
    size += chunk.length;  //累加緩衝數據的長度
  });

  

  res.on('end',function(err){

    var data = Buffer.concat(chunks, size);  //Buffer.concat將chunks數組中的緩衝數據拼接起來,返回一個新的Buffer對象賦值給data

    console.log(Buffer.isBuffer(data));    //可經過Buffer.isBuffer()方法判斷變量是否爲一個Buffer對象

    

    var base64Img = data.toString('base64');  //將Buffer對象轉換爲字符串並以base64編碼格式顯示

    console.log(base64Img);   //進入終端terminal,而後進入index.js所在的目錄,

                   //在終端中輸入node index.js

                   //打印出來的就是圖片的base64編碼格式,格式以下    

  });

});

 

抓取網絡圖片後轉換爲base64編碼格式,格式以下:

iVBORw0KGgoAAAANSUhEUgAAAKQAAABsCAYAAADkDhmYAAAABmJLR0QA/wD/AP+gvaeTAAAQQUlEQVR42u2dd5gV1RmH34UVWIrIggJGkKJoAI2ixqixYW9oohgTxSTG2GskkURjN/aW2GNQY0eDqFERC7FLVCJFRLGAXURAUZosmz9+Z5zh7tw7M/dOu7vnfZ777N07Z2bOzP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U9qgE+M+lPRgtXFWuXT0S+7LbmGjuhl3G2+f1X+LuLMfmejdqmxaaRrIPGGrxCQZQKD93MfZjxf9BGjS2lWnkYAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAABJRU5ErkJggg==

 

Question:

1:把圖片轉換爲base64編碼有什麼用?

2:轉換後的base64編碼怎麼使用?

 

Answer:

1.將圖片轉換爲base64編碼能夠實現網頁圖片在網速很差的時候先於內容加載和減小http的請求次數來減小服務器的負擔;

 

2.使用方法(以png爲例),上面一大坨的編碼簡寫爲abc

  background:url("data:image/png;base64,abc")  no-repeat;

  假如轉換的是其餘格式的圖片(如gif)則改寫成background:url("data:image/gif;base64,abc")  no-repeat;

 

如說得不妥,歡迎留言指出,謝謝

相關文章
相關標籤/搜索