From fe4e737082ff20c33c92ec813e8dda558be941c9 Mon Sep 17 00:00:00 2001 From: Lauren Liberda Date: Sun, 23 May 2021 14:08:24 +0200 Subject: [PATCH] scale thumbnail support (#1) --- src/index.ts | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/index.ts b/src/index.ts index 54f577d..2ba4f82 100644 --- a/src/index.ts +++ b/src/index.ts @@ -116,7 +116,15 @@ media.get( media.get('/thumbnail/:serverName/:mediaId', async (ctx) => { const { serverName, mediaId } = ctx.params; - if (typeof ctx.query.width !== 'string' || typeof ctx.query.height !== 'string') return; + if ( + typeof ctx.query.width !== 'string' || + typeof ctx.query.height !== 'string' || + typeof ctx.query.method !== 'string' + ) { + return; + } + const { method } = ctx.query; + assert(['crop', 'scale'].includes(method)); const width = parseInt(ctx.query.width, 10); const height = parseInt(ctx.query.height, 10); @@ -144,7 +152,10 @@ media.get('/thumbnail/:serverName/:mediaId', async (ctx) => { ); } if (file && file.statusCode === 200) { - const img = await sharp(file.body).resize(width, height).toBuffer({ resolveWithObject: true }); + const resizer = sharp(file.body).resize(width, height, { + fit: method === 'crop' ? 'cover' : 'inside', + }); + const img = await resizer.toBuffer({ resolveWithObject: true }); ctx.res.statusCode = 200; ctx.res.setHeader('content-type', `image/${img.info.format}`); ctx.res.write(img.data);