图片转base64方法总结

将图片转为base64格式是一种比较常见的需求,今天就总结一下在浏览器中和服务器上比较常用的几种方法。

通过canvas将图片转base64


<html lang='zh'>
<head>
  <meta charset='UTF-8' />
  <meta name='viewport' content='width=device-width, initial-scale=1.0' />
  <meta http-equiv='X-UA-Compatible' content='ie=edge' />
  <title>通过canvas将图片转base64title>
head>
<body>
  <img src=""/>
  <script type='text/javascript'>
    /**
     * @desc 图片转base64
     * @args {String} imgUrl 图片地址
     * @args {Number} quality 图片质量
     */
    function getBase64Image(imgUrl, quality = 0.5) {
      var img = new Image();
      img.src = imgUrl
      return new Promise(resolve => {
        img.onload = function() {
          var canvas = document.createElement("canvas");
          canvas.width = img.width;
          canvas.height = img.height;
          var ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0, img.width, img.height);
          dataURL = canvas.toDataURL('image/jpeg', quality);
          resolve(dataURL)
        }
      })
    }
    // 仅支持本地图片
    getBase64Image("./pic.png", 0.8).then(function(base64) {
      console.log(base64)
      document.querySelector('img').src = base64
    })
  script>
body>
html>

通过html2canvas将页面转化为图片(推荐)


<html lang='zh'>
<head>
  <meta charset='UTF-8' />
  <meta name='viewport' content='width=device-width, initial-scale=1.0' />
  <meta http-equiv='X-UA-Compatible' content='ie=edge' />
  <title>通过html2canvas将页面转化为图片title>
head>
<body> 
  
  <img src='https://wx.qlogo.cn/mmopen/vi_32/UQoHn9hFNXbeJD1EdLAdBhWfFcIBKViajWOicl2uticOVNs1FKdO5d80QLVjPCnL3LY53gs0EbmIFl5zDgLI7oGTw/132'/>
  <script src="https://daoket.gitee.io/ai/js/html2canvas.min.js">script>
  <script type='text/javascript'>
    html2canvas(document.querySelector('img'), {useCORS: true}).then(function(canvas) {
      var base64 = canvas.toDataURL("image/jpeg", 0.1);
      document.body.appendChild(canvas);
      console.log(base64)

//    downloadImg(base64, "meme.png")
    });

    // 下载图片
    function downloadImg(base64, imgName) {
      var a = document.createElement("a");
      a.href = base64;
      a.download = imgName;
      a.click();
    }
  script>
body>
html>

通过node的fs.readFile转换

const fs = require('fs');

fs.readFile('./a.png', 'base64', (err, data) => {
  // 图片需要在data前加上 'data:image/png;base64,'
  console.log(data)
});

通过node的fs.createReadStream转换

var fs = require('fs');
var readStream = fs.createReadStream('./pic.png');

readStream.on('data', function (chunk) {
  console.log(chunk.toString('base64')) 
});

通过Buffer转化

let base64 = Buffer.from('把我转化为base64').toString('base64')
console.log(base64)

你可能感兴趣的:(js,node)