import md5 from "js-md5";
// 定义 Loading 对象
const ImgCache = {
data: {
error: "",
loading: "",
localPhat_normal: "cdvfile://localhost/cache/imgers/normal/@fileName@.jpg",
localPhat_compress:
"cdvfile://localhost/cache/imgers/compress/@fileName@.jpg"
},
// install 是默认的方法。当外界在 use 这个组件的时候,就会调用本身的 install 方法,同时传一个 Vue 这个类的参数。
install: function(Vue, options = {}) {
var that = this;
if (options.loading) {
that.data.loading = options.loading;
}
if (options.error) {
that.data.error = options.error;
}
//重写懒加载
Vue.directive("lazy", {
inserted: function(el, binding, vnode) {
debugger;
//给加载图片
el.src = that.data.loading;
el.setAttribute("lazy", "loading");
//本地加载
that.localload(binding.value, el);
}
});
},
localload: function(src, el) {
var that = this;
//格式化url
src = src
.trim()
.toLocaleLowerCase()
.replace(/\/\//g, "/")
.replace(/:\//g, "://");
//如果是网络图片则判断本地是否缓存没有下载缓存有直接读取本地图片
if (
typeof device != "undefined" &&
(src.substring(0, 8) == "https://" || src.substring(0, 7) == "http://")
) {
var fileName = md5(src);
var localPhat = that.data.localPhat_normal.replace(
"@fileName@",
fileName
);
window.resolveLocalFileSystemURL(
localPhat,
function(fileEntry) {
//存在
el.src = fileEntry.toURL();
el.setAttribute("lazy", "loaded");
},
function(error) {
// 本地不存在图片
that.download(
src,
localPhat,
function(data) {
el.src = data;
el.setAttribute("lazy", "loaded");
},
function() {
el.src = that.data.error;
el.setAttribute("lazy", "error");
}
);
}
);
} else {
//本地图片正常加载
var tempImg = new Image();
tempImg.src = src;
tempImg.onload = function() {
el.src = this.src;
el.setAttribute("lazy", "loaded");
};
tempImg.onerror = function() {
el.src = that.data.error;
el.setAttribute("lazy", "error");
};
}
},
download: function(src, localPhat, callBack, error) {
//不存在下载
var fileTransfer = new FileTransfer();
fileTransfer.download(
src,
localPhat,
function(entry) {
//下载成功
callBack(entry.toURL());
},
function(e) {
//下载异常
error();
},
true
);
},
compress: function(img) {
var height = img.height;
var width = img.width;
var base64data = "";
var can = document.createElement("canvas");
can.height = height;
can.width = width;
var casimg = can.getContext("2d");
casimg.clearRect(0, 0, width, height);
casimg.drawImage(img, 0, 0, width, height);
base64data = can.toDataURL("image/jpeg"); //获取在canvas元素中的图片截图base64编码
var size = Math.round(dataURLtoBlob(base64data).size / 1024); //获取压缩前的图片大小
var maxsize = 800; //设置压缩后的最大值
if (size > maxsize) {
if (size < 1300) {
img.height = Math.round(height * (3 / 4));
img.width = Math.round(width * (3 / 4));
return scaleimg(img);
} else if (size < 1800) {
img.height = Math.round(height * (2 / 3));
img.width = Math.round(width * (2 / 3));
return scaleimg(img);
} else {
img.height = Math.round(height / 2);
img.width = Math.round(width / 2);
return scaleimg(img);
}
} else {
console.log("压缩后大小" + size);
return base64data;
}
}
};
// 导出
export default ImgCache;