2022-07-01 15:47:48 +00:00
|
|
|
import sharp from 'sharp';
|
2022-09-22 19:48:14 +00:00
|
|
|
import { BaseSSRService, isOutputFormatSupportsAlpha } from '../loaders/index.js';
|
|
|
|
import type { SSRImageService } from '../loaders/index.js';
|
|
|
|
import type { OutputFormat, TransformOptions } from './index.js';
|
2022-07-01 15:47:48 +00:00
|
|
|
|
2022-09-22 19:48:14 +00:00
|
|
|
class SharpService extends BaseSSRService {
|
2022-07-01 15:47:48 +00:00
|
|
|
async transform(inputBuffer: Buffer, transform: TransformOptions) {
|
2022-08-05 22:32:45 +00:00
|
|
|
const sharpImage = sharp(inputBuffer, { failOnError: false, pages: -1 });
|
2022-07-01 17:43:26 +00:00
|
|
|
|
2022-07-22 23:01:56 +00:00
|
|
|
// always call rotate to adjust for EXIF data orientation
|
|
|
|
sharpImage.rotate();
|
|
|
|
|
2022-07-01 15:47:48 +00:00
|
|
|
if (transform.width || transform.height) {
|
2022-07-01 19:56:43 +00:00
|
|
|
const width = transform.width && Math.round(transform.width);
|
|
|
|
const height = transform.height && Math.round(transform.height);
|
2022-09-09 20:13:59 +00:00
|
|
|
|
|
|
|
sharpImage.resize({
|
|
|
|
width,
|
|
|
|
height,
|
|
|
|
fit: transform.fit,
|
|
|
|
position: transform.position,
|
|
|
|
background: transform.background,
|
|
|
|
});
|
2022-07-01 15:47:48 +00:00
|
|
|
}
|
2022-07-01 17:43:26 +00:00
|
|
|
|
2022-07-01 15:47:48 +00:00
|
|
|
if (transform.format) {
|
|
|
|
sharpImage.toFormat(transform.format, { quality: transform.quality });
|
2022-09-20 20:25:45 +00:00
|
|
|
|
|
|
|
if (transform.background && !isOutputFormatSupportsAlpha(transform.format)) {
|
|
|
|
sharpImage.flatten({ background: transform.background });
|
|
|
|
}
|
2022-07-01 15:47:48 +00:00
|
|
|
}
|
2022-07-01 17:43:26 +00:00
|
|
|
|
2022-07-01 15:47:48 +00:00
|
|
|
const { data, info } = await sharpImage.toBuffer({ resolveWithObject: true });
|
2022-07-01 17:43:26 +00:00
|
|
|
|
2022-07-01 15:47:48 +00:00
|
|
|
return {
|
|
|
|
data,
|
|
|
|
format: info.format as OutputFormat,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-09-08 18:41:17 +00:00
|
|
|
const service: SSRImageService = new SharpService();
|
2022-07-01 15:47:48 +00:00
|
|
|
|
|
|
|
export default service;
|