-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #14 from jwblangley/image-compression
Image compression
- Loading branch information
Showing
10 changed files
with
672 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
const jimp = require('jimp') | ||
|
||
// 16 MP | ||
const MAX_SIZE = 16 * 1000 * 1000 | ||
// 80% Quality | ||
const QUALITY = 75 | ||
|
||
const EPSILON = 0.01 | ||
|
||
function processImage(input, cb, overwrite = true) { | ||
jimp.read(input, (err, img) => { | ||
if (err) { | ||
cb(err) | ||
return | ||
} | ||
const split = input.match(/(.*)\.(.*)/) | ||
const filename = split[1] | ||
const fileExt = split[2] | ||
|
||
const size = img.bitmap.width * img.bitmap.height | ||
|
||
if (size < EPSILON * MAX_SIZE) { | ||
return | ||
} | ||
|
||
const factor = Math.sqrt(MAX_SIZE / size) | ||
img | ||
.scale(factor) | ||
.quality(QUALITY) | ||
.write(filename + (overwrite ? '' : '-processed') + '.' + fileExt) | ||
if (cb) { | ||
cb() | ||
} | ||
}) | ||
} | ||
|
||
async function processImageSync(input, overwrite = true) { | ||
await jimp.read(input) | ||
.then(img => { | ||
const split = input.match(/(.*)\.(.*)/) | ||
const filename = split[1] | ||
const fileExt = split[2] | ||
|
||
const size = img.bitmap.width * img.bitmap.height | ||
|
||
if (size < EPSILON * MAX_SIZE) { | ||
return | ||
} | ||
|
||
const factor = Math.sqrt(MAX_SIZE / size) | ||
return img | ||
.scale(factor) | ||
.quality(QUALITY) | ||
.write(filename + (overwrite ? '' : '-processed') + '.' + fileExt) | ||
}) | ||
.catch(err => console.error(err)) | ||
} | ||
|
||
module.exports = { | ||
processImage, | ||
processImageSync | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.