TypeScript 图像处理:库与工具
TypeScript 是一种强大的编程语言,通过静态类型扩展了 JavaScript。在现代 Web 应用开发中,经常需要处理图像:调整尺寸、转换格式、应用滤镜或分析像素。本文将介绍 TypeScript 中用于图像处理的主要库和工具、它们的功能以及使用示例。
流行的图像处理库
有几种流行的库可以与 TypeScript 完美集成。下面我们来详细了解每一个。
Sharp
Sharp 是一个基于原生 libvips 模块的高性能图像处理库。它非常适合 Node.js 上的服务器端应用。Sharp 支持多种格式(JPEG、PNG、WebP、AVIF、TIFF),并能以最小的内存消耗执行操作。
TypeScript 使用示例:
import sharp from 'sharp';
async function resizeImage(inputPath: string, outputPath: string, width: number, height: number): Promise<void> { try { await sharp(inputPath) .resize(width, height, { fit: 'cover' }) .toFile(outputPath); console.log('图像已成功调整大小'); } catch (error) { console.error('处理时出错:', error); }}
// 使用resizeImage('input.jpg', 'output.jpg', 800, 600);Sharp 的主要功能:
- 调整大小和裁剪
- 格式转换
- 添加水印
- 旋转和翻转
- 压缩质量控制
Jimp
Jimp(JavaScript 图像处理程序)是一个纯 JavaScript 库,无需原生依赖。它既可以在 Node.js 中运行,也可以在浏览器中运行。Jimp 安装更简单,但在处理大文件时比 Sharp 慢。
在 TypeScript 中使用 Jimp 的示例:
import Jimp from 'jimp';
async function applyFilter(imagePath: string, outputPath: string): Promise<void> { const image = await Jimp.read(imagePath); image .resize(300, Jimp.AUTO) // 保持比例 .greyscale() // 转换为灰度 .contrast(0.5) // 增加对比度 .write(outputPath); console.log('滤镜已应用');}
applyFilter('photo.jpg', 'photo-edited.jpg');Jimp 的功能:
- 基本操作:resize、crop、rotate
- 色彩效果:sepia、greyscale、brightness
- 透明度处理和文本叠加
- 支持超过 20 种图像格式
用于浏览器应用的 Canvas API
如果您正在使用 TypeScript 开发客户端应用,可以使用内置的 Canvas API。这不是一个库,而是用于绘制和处理图像的标准 Web 接口。TypeScript 为所有 Canvas 方法提供了类型。
在 Canvas 上加载和处理图像的示例:
function processImageOnCanvas(imageUrl: string): void { const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); if (!ctx) { throw new Error('Canvas 不受支持'); } const img = new Image(); img.onload = () => { canvas.width = img.width / 2; canvas.height = img.height / 2; ctx.drawImage(img, 0, 0, canvas.width, canvas.height); // 应用模糊效果 ctx.filter = 'blur(4px)'; ctx.drawImage(canvas, 0, 0); // 获取像素数据 const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height); console.log('第一个像素:', imageData.data.slice(0, 4)); };