在JavaScript中为图片添加水印并上传通常涉及以下几个步骤:
<input type="file" id="imageUpload" accept="image/*" />
<button onclick="uploadImage()">上传</button>
function addWatermark(image, watermarkText) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
const width = image.width;
const height = image.height;
canvas.width = width;
canvas.height = height;
// Draw the original image
ctx.drawImage(image, 0, 0);
// Draw the watermark text
ctx.font = '30px Arial';
ctx.fillStyle = 'rgba(255, 255, 255, 0.5)';
ctx.fillText(watermarkText, 10, 30);
return canvas.toDataURL('image/png');
}
function uploadImage() {
const fileInput = document.getElementById('imageUpload');
const file = fileInput.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
const watermarkedImage = addWatermark(img, '我的水印');
const formData = new FormData();
formData.append('file', dataURLtoBlob(watermarkedImage), 'watermarked_image.png');
// 使用XMLHttpRequest或Fetch API上传formData
// 这里只是一个示例,实际应用中需要处理上传逻辑
console.log('准备上传:', formData);
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
}
}
function dataURLtoBlob(dataURL) {
const arr = dataURL.split(','), mime = arr[0]?.match(/:(.*?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n--){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}
通过以上步骤和代码示例,可以在JavaScript中实现图片加水印并上传的功能。
领取专属 10元无门槛券
手把手带您无忧上云