Fork me on GitHub

将图片URL转为base64

把小图片转存为base64格式,方便将小图片存储到数据库中。

依赖项

base64-img 1.0.4

小案例

http://www.qskxs.com/uploads/4/4152.jpg图片地址通过node.js获取并转为base64格式。

index.js

const base64Img = require('base64-img');
base64Img.requestBase64('http://www.qskxs.com/uploads/4/4152.jpg', function(err, res, body) {
  if (err) {
    console.log(err)
  } else {
    console.log(body) // data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/...
  }
})

把base64格式图片用img标签显示出来

index.html

<!DOCTYPE html>
<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>demo</title>
</head>
<body>
  <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/..." alt="">
</body>
</html>