第一步
window['webBase64String'] = (param) => {
var fileList = param.files[0];
var reader = new FileReader();
reader.readAsDataURL(fileList);
reader.onload = (event) => {
let image: any = new Image() //新建一个img标签(还没嵌入DOM节点)
let dataImg = event.target.result;
let num = 1;
image.src = event.target.result
image.onload = () => {
cc.log(fileList.size)
// 由于不能将太多Base64字符给服务端发过于,咱们压缩一下
// 如果想支持更大图片,请继续加判断,增加除数
if (fileList.size > 5000000) {
DialogManager.showTips('文件大小不能大于5M!')
}
let canvas = document.createElement('canvas');
let context = canvas.getContext('2d');
let imageWidth = image.width / num; //压缩后图片的大小
let imageHeight = image.height / num;
canvas.width = imageWidth;
canvas.height = imageHeight;
context.drawImage(image, 0, 0, imageWidth, imageHeight);
dataImg = canvas.toDataURL('image/png');
this.editIcon(dataImg)
cc.log('dataImg===', dataImg);
//此时的dataImg就是你要上传给服务器的字符
}
};
};
setHeadPic(src, node: cc.Node): void {
let imgElement = new Image();
// cc.BufferedImage
imgElement.src = src;
setTimeout(function () {
let sprite = new cc.Texture2D();
sprite.initWithElement(imgElement);
sprite.handleLoadedTexture();
let spriteFrame = new cc.SpriteFrame(sprite);
let sp = node.getComponent(cc.Sprite);
sp.spriteFrame = spriteFrame;
setImageSize(node.getComponent(cc.Sprite), 263, 263)
}, 10);
}
第二步
document.getElementById("file").click();
editIcon(dataImg) {
setHeadPic(dataImg, this.icon.node)
}
第三步 index html 里面
<input id="file" type="file" accept="image/*" class="fileToUpload" style="opacity:0;position:absolute;"
οnchange="webBase64String(this)" />