获取图片信息
uni.chooseImage({
count: 6,
sizeType: ["original", "compressed"],
sourceType: ["camera"],
success: async function (result: any) {
if (!props.isMark) {
const res: any = await uploadFilePromise(result.tempFilePaths[0]);
if (res) {
show.value = false;
}
emit("handleFileList", res);
return;
}
show.value = true;
const reader = new FileReader();
reader.onload = async (e: any) => {
originalImage.value = e.target.result;
await addWatermark();
};
reader.readAsDataURL(result.tempFiles[0]);
},
});
添加水印
- 由于使用canvas添加水印后图片很大,所以压缩一下图片大小
- 使用
compressImg1
方法压缩图片大小
const addWatermark = () => {
const img = new Image();
img.onload = async () => {
const canvas = document.createElement("canvas");
const ctx: any = canvas.getContext("2d");
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img, 0, 0);
var fontSize = canvas.width > 600 ? canvas.width / 20 : 16;
console.log(fontSize, "fontSizefontSize字体大小---");
ctx.font = fontSize + "px Arial";
let time = moment().format("YYYY-MM-DD HH:MM:SS");
let height = canvas.height - 50;
let height1 = canvas.height - 20;
if (canvas.width > 600) {
height = canvas.height - 290;
height1 = canvas.height - 50;
}
const pixel = ctx.getImageData(10, height, 1, 1).data;
const luminance = 0.2126 * pixel[0] + 0.7152 * pixel[1] + 0.0722 * pixel[2];
const fontColor = luminance > 128 ? "black" : "#fff";
ctx.fillStyle = fontColor ;
ctx.fillText("时间:" + time, 15, height);
ctx.fillText(latLng.value, 15, height1);
watermarkedImage.value = await canvas.toDataURL("image/png", 0.8);
let imgURL = await compressImg1(watermarkedImage.value, 0.8);
console.log(getBase64ImageSize(imgURL), "图片大小11111111111111");
const result: any = await uploadFilePromise(imgURL);
if (result) {
show.value = false;
}
emit("handleFileList", result);
};
img.src = originalImage.value;
};
压缩图片的方法
export const compressImg1 = (base64, multiple)=> {
return new Promise((resolve, reject) => {
try {
if (!base64) {
return
}
const length = base64.length / 1024
let newImage = new Image()
let quality = 0.6
newImage.src = base64
newImage.setAttribute('crossOrigin', 'Anonymous')
let imgWidth,
imgHeight
let w = undefined
newImage.onload = function () {
w = this.width * multiple
imgWidth = this.width
imgHeight = this.height
let canvas = document.createElement('canvas')
let ctx = canvas.getContext('2d')
if (Math.max(imgWidth, imgHeight) > w) {
if (imgWidth > imgHeight) {
canvas.width = w
canvas.height = w * (imgHeight / imgWidth)
} else {
canvas.height = w
canvas.width = w * (imgWidth / imgHeight)
}
} else {
canvas.width = imgWidth
canvas.height = imgHeight
quality = 0.6
}
ctx.clearRect(0, 0, canvas.width, canvas.height)
ctx.drawImage(this, 0, 0, canvas.width, canvas.height)
let smallBase64 = canvas.toDataURL('image/jpeg', quality)
console.log(`压缩前:${length}KB`)
console.log(`压缩后:${smallBase64.length / 1024} KB`)
resolve(smallBase64)
}
}
catch (error) {
reject(error)
throw new Error(error)
}
})
}