首先呢,说一下开发背景&应用场景。
github上有一个gulp插件gulp-base64,是将css内的url('')中的图片转换成base64,
而我在自己开发中,自己有这么个需求想要将html中的图片转换成base64(包括<img/ src=" ">标签 && url('') 背景图片),
看了一下github上开源的gulp插件,功能都不太匹配,所以自己参考了一些开源的逻辑,自己编写了一个gulp插件,
有需要的可以直接拿去项目中,功能不完善的可以参考逻辑自己再改造~~
(实践过应用在HTML文件是没有问题的,按道理CSS文件中的图片应该也是可以匹配转换的,但是因为最近没什么时间也没这个需求所以还未实践过,后续实践过再进行声明修改)
gulp项目--plugin 路径参考:
(gulp-img-base64 index.js)plugin开发:
/**
* Created 2018/8/28.
* 将图片url转为base64
* @author joker.lee
*/
'use strict';
let through = require('through2');
let path = require('path');
let fs = require('fs');
module.exports = function(options) {
let opts = options || {};
let rule = opts.rule || /(<img.*?src=")(.*?\.png|jpe?g|gif|webp)(".*?>)/g || /url\([^\)]+\)/g;
let initFileType = opts.filetype || 'html';
let baseDir = opts.baseDir || '.';
let currentPath = __dirname + '../../../' + baseDir;
function transferImage(data){
/* <img/> label 标签图片 */
let imgRule = opts.rule || /(<img.*?src=")(.*?\.png|jpe?g|gif|webp)(".*?>)/g;
let imgList = data.match(imgRule) || [];
if (imgList.length) {
imgList.forEach(function(item) {
let imageURL = item.replace(imgRule, '$2');
if (/^http|https:/.test(imageURL)) { /* 筛选过滤 */
return false;
}
let route = path.join(currentPath, imageURL);
let filepath = fs.realpathSync(route);
let extname = path.extname(imageURL).slice(1);
let imageContent = new Buffer(fs.readFileSync(filepath)).toString('base64');
data = data.replace(imageURL, 'data:image/' + extname.toLowerCase() + ';base64,' + imageContent);
});
}
/* url('background-image') 背景图片*/
let urlRule = opts.rule || /url\([^\)]+\)/g;
let urlImgList = data.match(urlRule) || [];
if (urlImgList.length) {
urlImgList.forEach(function(item) {
let imageURL = item.replace(/\(|\)|\'/g, '');
imageURL = imageURL.replace(/^url/g, '');
if (/^http|https:/.test(imageURL)) { /* 筛选过滤 */
return false;
}
let route = path.join(currentPath, imageURL);
let filepath = fs.realpathSync(route);
let extname = path.extname(imageURL).slice(1);
let imageContent = new Buffer(fs.readFileSync(filepath)).toString('base64');
data = data.replace(item, 'url(\'data:image/' + extname.toLowerCase() + ';base64,' + imageContent + '\')');
});
}
return data;
}
function rebase(file, encoding, callback) {
if (file.isNull()) {
return callback(null, file);
}
if (file.isStream()) {
return callback(createError(file, 'Streaming not supported'));
}
let content = file.contents.toString();
content = transferImage(content);
file.contents = new Buffer(content);
this.push(file);
callback(null, file);
}
return through.obj(rebase);
};
(gulpfile.js)plugin调用:
/**
* Created 2018/8/28.
* @author joker.lee
*/
let gulp = require('gulp');
let base64 = require('./build/gulp-img-base64');
/*
* 图片转base64
*/
gulp.task('base64', ['clean'], function () {
gulp.src('./src/view/*.html')
.pipe(base64())
.pipe(gulp.dest('./dist/view'));
});
github地址(使用示例内容后续完善):https://github.com/Joker-Lee/gulp-img-base64