import { Injectable } from '@nestjs/common'; import sharp from 'sharp'; /** * Sharp 图片处理服务 * 基于 NestJS 官方示例实现 * 参考: https://docs.nestjs.cn/fundamentals/dependency-injection * 对应 Java: ImageUtils */ @Injectable() export class SharpService { /** * 获取 sharp 实例 */ getSharp() { return sharp; } /** * 调整图片大小 */ async resize( input: Buffer | string, width: number, height?: number, options?: sharp.ResizeOptions, ): Promise { return sharp(input).resize(width, height, options).toBuffer(); } /** * 生成缩略图 */ async thumbnail( input: Buffer | string, size: number, options?: sharp.ResizeOptions, ): Promise { return sharp(input) .resize(size, size, { ...options, fit: 'cover' }) .toBuffer(); } /** * 压缩图片 */ async compress( input: Buffer | string, quality: number = 80, ): Promise { return sharp(input).jpeg({ quality }).toBuffer(); } /** * 转换图片格式 */ async convert( input: Buffer | string, format: 'jpeg' | 'png' | 'webp' | 'gif' | 'tiff', ): Promise { return sharp(input).toFormat(format).toBuffer(); } /** * 获取图片信息 */ async metadata(input: Buffer | string): Promise { return sharp(input).metadata(); } /** * 裁剪图片 */ async crop( input: Buffer | string, left: number, top: number, width: number, height: number, ): Promise { return sharp(input).extract({ left, top, width, height }).toBuffer(); } /** * 旋转图片 */ async rotate(input: Buffer | string, angle: number): Promise { return sharp(input).rotate(angle).toBuffer(); } /** * 翻转图片 */ async flip(input: Buffer | string): Promise { return sharp(input).flip().toBuffer(); } /** * 镜像图片 */ async flop(input: Buffer | string): Promise { return sharp(input).flop().toBuffer(); } /** * 模糊图片 */ async blur(input: Buffer | string, sigma: number): Promise { return sharp(input).blur(sigma).toBuffer(); } /** * 锐化图片 */ async sharpen( input: Buffer | string, sigma?: number, flat?: number, jagged?: number, ): Promise { return sharp(input).sharpen(sigma, flat, jagged).toBuffer(); } /** * 调整亮度 */ async modulate( input: Buffer | string, brightness: number = 1, ): Promise { return sharp(input).modulate({ brightness }).toBuffer(); } /** * 调整对比度 */ async linear(input: Buffer | string, a: number, b: number): Promise { return sharp(input).linear(a, b).toBuffer(); } /** * 添加水印 */ async composite( input: Buffer | string, overlay: Buffer | string, options?: sharp.OverlayOptions, ): Promise { return sharp(input) .composite([{ input: overlay, ...options }]) .toBuffer(); } /** * 生成图片哈希 */ async hash(input: Buffer | string): Promise { const metadata = await sharp(input).metadata(); return `${metadata.width}x${metadata.height}-${metadata.format}`; } }