在 TypeScript 中处理图像:缩放和裁剪
在现代 Web 开发中,图像处理是最常见的任务之一。TypeScript 凭借其强类型特性和与 Node.js 的集成,能够创建可靠且高效的图像缩放 (resize) 和裁剪 (crop) 工具。在本文中,我们将介绍两个流行的库:Sharp(服务器端处理)和 Jimp(纯 JavaScript),以及使用 Canvas API 在浏览器中进行原生处理的方法。
1. 安装和配置 TypeScript 项目
首先,创建一个项目并安装必要的依赖项:
npm init -ynpm install typescript @types/node sharp jimpnpx tsc --init在 tsconfig.json 文件中,确保 "module": "commonjs" 和 "target": "ES2020" 已设置。
2. Sharp 库——快速的服务器端处理
Sharp 使用原生模块 libvips,提供高性能。适用于服务器端应用程序(NestJS、Express)。
2.1. 使用 Sharp 调整大小 (resize)
resize() 方法接受宽度和高度。可以只指定一个参数——第二个参数将按比例计算。
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', // 'cover', 'contain', 'fill', 'inside', 'outside' position: 'center' // 使用 cover 模式时裁剪的位置 }) .toFile(outputPath); console.log(`图像已调整大小:${outputPath}`); } catch (error) { console.error('resize 错误:', error); }}
// 使用示例resizeImage('input.jpg', 'output_800x600.jpg', 800, 600);2.2. 使用 Sharp 进行裁剪 (crop)
extract() 方法允许裁剪出一个矩形区域。参数:left、top、width、height。
async function cropImage( inputPath: string, outputPath: string, left: number, top: number, cropWidth: number, cropHeight: number): Promise<void> { try { await sharp(inputPath) .extract({ left, top, width: cropWidth, height: cropHeight }) .toFile(outputPath); console.log(`裁剪完成:${outputPath}`); } catch (error) { console.error('crop 错误:', error); }}
// 示例:从 800x600 的图像中裁剪出中心 400x400 的区域cropImage('input.jpg', 'cropped_center.jpg', 200, 100, 400, 400);2.3. 组合 resize 和 crop
Sharp 允许将操作链接起来。例如,先缩小,再裁剪:
async function resizeAndCrop(inputPath: string, outputPath: string): Promise<void> { await sharp(inputPath) .resize(500, 500, { fit: 'inside' }) // 缩小到 500x500 而不裁剪 .extract({ left: 50, top: 50, width: 400, height: 400 }) // 裁剪中心区域 .toFile(outputPath);}
resizeAndCrop('input.jpg', 'processed.jpg');3. Jimp 库——无原生依赖的纯 JavaScript
Jimp 使用纯 JavaScript 运行,无需安装额外的系统库。非常适合隔离环境(例如 AWS Lambda)。
3.1. 安装 Jimp
npm install jimpnpm install @types/jimp // 用于 TypeScript3.2. 使用 Jimp 调整大小 (resize)
import Jimp from 'jimp';
async function resizeWithJimp(inputPath: string, outputPath: string, width: number, height: number): Promise<void> { try { const image = await Jimp.read(inputPath); image.resize(width, height, Jimp.RESIZE_BILINEAR); // 算法:BILINEAR, BICUBIC, NEAREST_NEIGHBOR awa