}else{
// 输入框图片显示缩小10倍
imgWidth = this.width/10;
imgHeight = this.height/10;
// 图片宽度大于1920,图片压缩5倍
if(this.width>1920){
// 真实比例缩小5倍
scale = 5;
}
}
// 设置可编辑div中图片宽高
img.width = imgWidth;
img.height = imgHeight;
// 压缩图片,渲染页面
that.compressPic(imgContent,scale,function (newBlob,newBase) {
// 删除可编辑div中的图片名称
that.$refs.msgInputContainer.textContent = oldText;
img.src = newBase; //设置链接
// 图片渲染
that.$refs.msgInputContainer.append(img);
that.$fullScreenLoading.hide();
});
};
};
reader.readAsDataURL(file);
});
base64图片压缩函数
// 参数: base64地址,压缩比例,回调函数(返回压缩后图片的blob和base64)
compressPic:function(base64, scale, callback){
const that = this;
let _img = new Image();
_img.src = base64;
_img.onload = function() {
let _canvas = document.createElement("canvas");
let w = this.width / scale;
let h = this.height / scale;
_canvas.setAttribute("width", w);
_canvas.setAttribute("height", h);
_canvas.getContext("2d").drawImage(this, 0, 0, w, h);
let base64 = _canvas.toDataURL("image/jpeg");
// 当canvas对象的原型中没有toBlob方法的时候,手动添加该方法
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
value: function (callback, type, quality) {
let binStr = atob(this.toDataURL(type, quality).split(',')[1]),
len = binStr.length,
arr = new Uint8Array(len);
for (let i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i);
}
callback(new Blob([arr], {type: type || 'image/png'}));
}
});
}else{
_canvas.toBlob(function(blob) {
if(blob.size > 1024*1024){
that.compressPic(base64, scale, callback);
}else{
callback(blob, base64);
}
}, "image/jpeg");
}
}
}完善消息发送函数,获取输入框里的所有子元素,找出base64图片将其转为文件并上传至服务器(此处需要注意:base64转文件时,需要用正则表达式删掉base64图片的前缀),将当前图片地址推送至websocket服务。
对下述代码有不理解的地方,可阅读我的另一篇文章:Vue实现图片与文字混输,
sendMessage: function (event) {
if (event.keyCode === 13) {
// 阻止编辑框默认生成div事件
event.preventDefault();
let msgText = "";
// 获取输入框下的所有子元素
let allNodes = event.target.childNodes;
for (let item of allNodes) {
// 判断当前元素是否为img元素










