Skip to content

Commit

Permalink
Merge pull request #434 from saplingjs/feature/thumbnails
Browse files Browse the repository at this point in the history
Generate thumbnails for image uploads
  • Loading branch information
groenroos authored Mar 20, 2022
2 parents 798f4e3 + 1195a8e commit a78f007
Show file tree
Hide file tree
Showing 6 changed files with 1,433 additions and 884 deletions.
12 changes: 12 additions & 0 deletions core/loadConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,18 @@ export function digest() {
upload: {
type: 'local',
destination: 'public/uploads',
thumbnails: [
{
name: 'web',
width: 1280,
},
{
name: 'thumb',
width: 128,
height: 128,
fit: 'cover',
},
],
},
port: argv.port || this.opts.port || 3000,
url: '',
Expand Down
27 changes: 26 additions & 1 deletion lib/Uploads.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ import fileUpload from 'express-fileupload';
import filenamify from 'filenamify';
import { unusedFilename } from 'unused-filename';
import imageSize from 'image-size';
import sharp from 'sharp';

import SaplingError from './SaplingError.js';
import Response from './Response.js';
import Utils from './Utils.js';
import Validation from './Validation.js';


Expand Down Expand Up @@ -107,8 +109,9 @@ export default class Uploads {
mimetype: file.mimetype,
};

/* If it's an image, get the width and height */
/* If it's an image */
if (file.group === 'image') {
/* Get the width and height */
const dimensions = await imageSize(file.tempFilePath);
fileObject.width = dimensions.width;
fileObject.height = dimensions.height;
Expand All @@ -120,6 +123,28 @@ export default class Uploads {
validator.validateFileMinheight(dimensions, fileField, rule);
validator.validateFileMaxheight(dimensions, fileField, rule);
}

/* Generate thumbnails, if any */
const thumbDefinition = rule && rule.thumbnails ? rule.thumbnails : this.app.config.upload.thumbnails;
const thumbs = thumbDefinition ? new Utils().coerceArray(thumbDefinition) : [];

for (const [i, thumb] of thumbs.entries()) {
/* Construct path for thumbnail */
const thumbPath = path.join(this.app.uploads.uploadDir, '/thumbs/', thumb.name || i);
if (!fs.existsSync(thumbPath)) {
fs.mkdirSync(thumbPath, { recursive: true });
}

/* Resize according to options, and save */
await sharp(file.tempFilePath)
.rotate() /* Rotate for EXIF orientation */
.resize({
width: thumb.width,
height: thumb.height,
fit: thumb.fit || 'cover',
})
.toFile(await unusedFilename(path.join(thumbPath, filenamify(file.name))));
}
}

/* If there are any errors, give up */
Expand Down
Loading

0 comments on commit a78f007

Please sign in to comment.