transform-image.ts 1.0 KB

1234567891011121314151617181920212223242526272829303132
  1. import sharp from 'sharp';
  2. import { ResizeOptions } from 'sharp';
  3. import { ImageTransformPreset } from './plugin';
  4. /**
  5. * Applies transforms to the given image according to the query params passed.
  6. */
  7. export async function transformImage(
  8. originalImage: Buffer,
  9. queryParams: Record<string, string>,
  10. presets: ImageTransformPreset[],
  11. ): Promise<sharp.Sharp> {
  12. let width = +queryParams.w || undefined;
  13. let height = +queryParams.h || undefined;
  14. let mode = queryParams.mode || 'crop';
  15. if (queryParams.preset) {
  16. const matchingPreset = presets.find(p => p.name === queryParams.preset);
  17. if (matchingPreset) {
  18. width = matchingPreset.width;
  19. height = matchingPreset.height;
  20. mode = matchingPreset.mode;
  21. }
  22. }
  23. const options: ResizeOptions = {};
  24. if (mode === 'crop') {
  25. options.position = sharp.strategy.entropy;
  26. } else {
  27. options.fit = 'inside';
  28. }
  29. return sharp(originalImage).resize(width, height, options);
  30. }