Files
wwjcloud/src/common/libraries/sharp/sharp.service.ts

162 lines
3.2 KiB
TypeScript
Raw Normal View History

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<Buffer> {
return sharp(input).resize(width, height, options).toBuffer();
}
/**
*
*/
async thumbnail(
input: Buffer | string,
size: number,
options?: sharp.ResizeOptions,
): Promise<Buffer> {
return sharp(input)
.resize(size, size, { ...options, fit: 'cover' })
.toBuffer();
}
/**
*
*/
async compress(
input: Buffer | string,
quality: number = 80,
): Promise<Buffer> {
return sharp(input).jpeg({ quality }).toBuffer();
}
/**
*
*/
async convert(
input: Buffer | string,
format: 'jpeg' | 'png' | 'webp' | 'gif' | 'tiff',
): Promise<Buffer> {
return sharp(input).toFormat(format).toBuffer();
}
/**
*
*/
async metadata(input: Buffer | string): Promise<sharp.Metadata> {
return sharp(input).metadata();
}
/**
*
*/
async crop(
input: Buffer | string,
left: number,
top: number,
width: number,
height: number,
): Promise<Buffer> {
return sharp(input).extract({ left, top, width, height }).toBuffer();
}
/**
*
*/
async rotate(input: Buffer | string, angle: number): Promise<Buffer> {
return sharp(input).rotate(angle).toBuffer();
}
/**
*
*/
async flip(input: Buffer | string): Promise<Buffer> {
return sharp(input).flip().toBuffer();
}
/**
*
*/
async flop(input: Buffer | string): Promise<Buffer> {
return sharp(input).flop().toBuffer();
}
/**
*
*/
async blur(input: Buffer | string, sigma: number): Promise<Buffer> {
return sharp(input).blur(sigma).toBuffer();
}
/**
*
*/
async sharpen(
input: Buffer | string,
sigma?: number,
flat?: number,
jagged?: number,
): Promise<Buffer> {
return sharp(input).sharpen(sigma, flat, jagged).toBuffer();
}
/**
*
*/
async modulate(
input: Buffer | string,
brightness: number = 1,
): Promise<Buffer> {
return sharp(input).modulate({ brightness }).toBuffer();
}
/**
*
*/
async linear(input: Buffer | string, a: number, b: number): Promise<Buffer> {
return sharp(input).linear(a, b).toBuffer();
}
/**
*
*/
async composite(
input: Buffer | string,
overlay: Buffer | string,
options?: sharp.OverlayOptions,
): Promise<Buffer> {
return sharp(input)
.composite([{ input: overlay, ...options }])
.toBuffer();
}
/**
*
*/
async hash(input: Buffer | string): Promise<string> {
const metadata = await sharp(input).metadata();
return `${metadata.width}x${metadata.height}-${metadata.format}`;
}
}