Skip to content

Commit

Permalink
added aspect-ratio support
Browse files Browse the repository at this point in the history
  • Loading branch information
friewerts committed Feb 22, 2020
1 parent fc9fef6 commit 17a30d4
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ Renditions are defined as objects with with and height (optional)
interface Rendition {
width: number;
height?: number;
aspectRatio?: string; // (e.g. 16:9)
}
```

23 changes: 22 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const getSrcFiles = (srcFiles: srcFilesDef): string[] => {
interface Rendition {
width: number;
height?: number;
aspectRatio?: string;
}

interface RenditionOptions extends Rendition {
Expand All @@ -34,10 +35,30 @@ const getFilename = (renditionOptions: Rendition, image: ImageOptions): string =
return base;
};

const hasAspectRatio = (options: Rendition): boolean => {
if (options.aspectRatio === undefined) return false;
const aspectParts = options.aspectRatio.split(':');
if (
aspectParts.length !== 2 ||
Number.isNaN(parseInt(aspectParts[0], 10)) ||
Number.isNaN(parseInt(aspectParts[1], 10))
)
return false;

return true;
};

const getHeight = (aspectRatio: string, width: number): number => {
const aspectParts = aspectRatio.split(':');

return Math.round((parseInt(aspectParts[1], 10) / parseInt(aspectParts[0], 10)) * width);
};

const createRendition = async (image: ImageOptions, options: Rendition): Promise<RenditionOptions> => {
const resizeOpts = [options.width];

if (options.height) resizeOpts.push(options.height);
if (hasAspectRatio(options)) resizeOpts.push(getHeight(options.aspectRatio || '1:1', options.width));
else if (options.height) resizeOpts.push(options.height);

const buffer = await sharp(image.buffer)
.resize(...resizeOpts)
Expand Down

0 comments on commit 17a30d4

Please sign in to comment.