在数字时代,保护自己的知识产权变得尤为重要。图片作为一种常见的数字资产,其版权保护尤为关键。使用 TypeScript 为图片添加水印是一种简单而有效的方法。以下,我将详细介绍如何使用 TypeScript 为图片添加水印,并保护你的作品不被盗用。
1. 准备工作
在开始之前,请确保你已经安装了 Node.js 和 npm。接下来,你还需要安装以下两个包:
sharp:一个高性能的图片处理库,用于图片的裁剪、缩放、水印添加等功能。typescript:TypeScript 编译器。
npm install sharp
npm install --save-dev typescript
2. 创建 TypeScript 文件
创建一个名为 addWatermark.ts 的 TypeScript 文件,并编写以下代码:
import sharp from 'sharp';
async function addWatermark(inputPath: string, outputPath: string, watermarkPath: string): Promise<void> {
await sharp(inputPath)
.composite([{ input: watermarkPath, gravity: 'southeast' }]) // 添加水印,并放置在右下角
.toFile(outputPath);
}
// 使用示例
addWatermark('input.jpg', 'output.jpg', 'watermark.png')
.then(() => console.log('Watermark added successfully!'))
.catch((error) => console.error('Error adding watermark:', error));
3. 编译 TypeScript 文件
使用 TypeScript 编译器将 TypeScript 文件编译为 JavaScript 文件:
tsc addWatermark.ts
这将生成一个 addWatermark.js 文件。
4. 运行脚本
使用 Node.js 运行编译后的 JavaScript 文件:
node addWatermark.js
这将自动为 input.jpg 添加水印,并保存为 output.jpg。
5. 添加自定义水印
为了更好地保护你的作品,你可以自定义水印内容,例如:
- 使用你的网站或品牌标志作为水印。
- 在水印中添加文字,如版权信息。
- 设置水印的透明度。
修改 addWatermark.ts 文件,添加以下代码:
async function addCustomWatermark(inputPath: string, outputPath: string, watermarkText: string): Promise<void> {
const watermark = await sharp('watermark.png') // 使用自定义的水印图片
.composite([{ input: 'watermark-text.png', gravity: 'southeast' }]) // 添加水印文字
.toBuffer();
await sharp(inputPath)
.composite([{ input: watermark, gravity: 'southeast' }]) // 将自定义水印添加到图片
.toFile(outputPath);
}
// 使用示例
addCustomWatermark('input.jpg', 'output.jpg', 'Copyright © 2021 Your Company')
.then(() => console.log('Custom watermark added successfully!'))
.catch((error) => console.error('Error adding custom watermark:', error));
现在,你可以使用 addCustomWatermark 函数添加自定义水印。
总结
使用 TypeScript 为图片添加水印是一种简单而有效的方法来保护你的作品。通过以上步骤,你可以轻松地为图片添加水印,并确保你的作品版权得到保护。
