<div id="imgList"></div>
<input type="file" accept="image/*" id="inputFile" (change)="inputFileChange()">
async inputFileChange() {
const imgList = document.getElementById('imgList');
const files = document.getElementById('inputFile')['files'][0];
console.log(files);
let img = await this.blobToImg(files);
console.log(img);
let canvas = this.imgToCanvas(img);
let blob = await this.watermark(canvas, '换表复核');
let newImage = await this.blobToImg(blob);
const newFiles = new window.File(
[blob],
files.name,
{ type: files.type }
);
this.fileList.push(newFiles);
newImage.style.width = '100px';
newImage.style.height = '100px';
newImage.style.margin = '20px 20px 20px 0';
imgList.appendChild(newImage);
}
blobToImg (blob) {
return new Promise((resolve) => {
if (blob) {
var render = new FileReader();
render.onload = function() {
let img = new Image()
img.src = render.result as any;
img.addEventListener('load', () => resolve(img))
}
render.readAsDataURL(blob);
}
}) as any;
}
imgToCanvas (img) {
let canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
let ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
return canvas;
}
watermark (canvas, text) {
return new Promise((resolve, reject) => {
let ctx = canvas.getContext('2d')
ctx.font = "24px 宋体"
ctx.fillStyle = "red"
ctx.textAlign = 'left'
ctx.fillText(text, 30, canvas.height - 30)
canvas.toBlob(blob => resolve(blob))
}) as any;
}