// 压缩图片的方法
function $imgCompressor(file,maxLength,quality){
if(!file || typeof file != 'object' || !file.type || file.type.indexOf('image')<0) {
return new Promise((resolve,reject)=>{
resolve(new Error('simplify-img-compressor:必须传入图片类型的文件对象'));
});
} else {
let maxImgLength = maxLength?maxLength:1200;// 最长边的长度最大值
let qua = quality?quality:0.6;// 压缩质量
let reader = new FileReader();
let compressImg = new Image();
reader.readAsDataURL(file);
return new Promise((resolve,reject) => {
reader.onload = function(e) {
let newUrl = e.target.result;
let c = document.createElement('canvas');
let img = document.createElement('img');
img.src = newUrl;
let ctx=c.getContext("2d");
let timmer = setInterval(function(){
if(reader.readyState == 2) {
clearInterval(timmer);
let imgHeight = img.height;
let imgWidth = img.width;
if(imgHeight>maxImgLength || imgWidth > maxImgLength) {
if(imgHeight>imgWidth) {
let rate = maxImgLength / imgHeight;
imgHeight = maxImgLength;
imgWidth = imgWidth*rate;
c.width = imgWidth;
c.height = imgHeight;
} else {
let rate = maxImgLength / imgWidth;
imgWidth = maxImgLength;
imgHeight = imgHeight*rate;
c.width = imgWidth;
c.height = imgHeight;
}
} else {
c.width = img.width;
c.height = img.height;
}
ctx.drawImage(img,0,0,imgWidth,imgHeight);
compressImg = c.toBlob(function(blob){
resolve({
file:blob,
name:file.name,
quality:qua,
maxImgLength:maxImgLength,
afterCompressorSize:(blob.size/1024).toFixed(2) + 'kb',
beforeCompressorSize:(file.size/1024).toFixed(2) + 'kb',
dataURL:c.toDataURL(),
});
},file.type,qua);
}
},200);
};
});
}
}
// 注册插件
CKEDITOR.plugins.add( 'uploadImg', { // 注册名为uploadImg的插件
icons: 'uploadImg',// 按钮的图标名
init: function( editor ) {
editor.addCommand( 'insertUploadImg', {
exec: function( editor ) {
// 此处定义点击按钮时的行为
// 此实例实现的功能是压缩所选择的图片并上传到服务器,然后将返回的内容添加到编辑器里
var $fileInput = document.createElement('input');
$fileInput.type = 'file';
$fileInput.accept = 'image/*';
$fileInput.click();
$fileInput.addEventListener('change',function(e){
var fileList = e.target.files;
console.log(fileList);
if(fileList.length>0) {
$imgCompressor(fileList[0],100,0.6).then((res)=>{
let formData = new FormData();
formData.append('file',res.file,res.name);
//创建异步对象
let xhr = new XMLHttpRequest();
xhr.open('post', 'http://www.ihtmlcss.com/phpcrm/tp5/public/index.php/admin/uploader/uploadPublic',true);
xhr.send(formData);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
let result = xhr.responseText;
if(typeof result == 'string') {result = JSON.parse(result)}
editor.insertHtml( "
} else {
alert('上传失败');
}
};
});
}
})
}
});
// 添加按钮到编辑器
editor.ui.addButton( 'uploadImg', {
label: 'Insert uploadImg',
command: 'insertUploadImg',
toolbar: 'insert'
});
}
});