diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7a1537b --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.idea +node_modules diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..af1beaf --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Call-Em-All + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..16fcb4b --- /dev/null +++ b/README.md @@ -0,0 +1,67 @@ +# image-optimist + +A utility for processing and converting images to the requirements of the modern web. + +## Install + +```shell +$ npm install --save-dev image-optimist +``` + +## Usage + +```js +const path = require('path'); +const imageOptimist = require('image-optimist'); + +(async () => { + await imageOptimist({ + sourcePath: path.join(__dirname, 'from'), + destinationPath: path.join(__dirname, 'to'), + }); +})(); +``` + +## API + +### imageOptimist(config) + +Returns `Promise`. + +#### config + +Type: `Object` + +##### sourcePath + +Type: `String` + +Set the source folder. +Keep in mind that the subfolders will be included in the processing and the output files will retain their original hierarchy. + +##### destinationPath + +Type: `String` + +Set the destination folder. The folder does not need to be empty, but images with the same name will be overwritten. + +##### mask? + +Type: `String`
+Default: `'*.{jpg,jpeg,png,svg,gif}'` + +See [Glob patterns](https://github.com/sindresorhus/globby#globbing-patterns). + +##### webp? + +Type: `Array || Boolean`
+Default: `[imageminWebp()]` + +By default, the optimal settings for generating WebP images are passed to the imageminWebp instance (see package source code for details). You can pass in your imageminWebp instance with the desired settings, or pass false if you want to disable the generation of images in WebP format. + +##### plugins? + +Type: `Array`
+Default: `[imageminMozjpeg(), imageminPngquant(), imageminSvgo(), imageminGifsicle()]` + +By default, optimal settings are passed to plugin instances (see package source code for details). You can pass your array with the plugins and settings you want. diff --git a/helpers/convertBytes.js b/helpers/convertBytes.js new file mode 100644 index 0000000..1324dd0 --- /dev/null +++ b/helpers/convertBytes.js @@ -0,0 +1,15 @@ +const convertBytes = (bytes) => { + const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; + + if (bytes === 0) + return 'n/a'; + + const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); + + if (i === 0) + return bytes + ' ' + sizes[i]; + + return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i]; +}; + +module.exports = convertBytes; diff --git a/helpers/getAllFiles.js b/helpers/getAllFiles.js new file mode 100644 index 0000000..b0a9408 --- /dev/null +++ b/helpers/getAllFiles.js @@ -0,0 +1,18 @@ +const fs = require('fs'); +const path = require('path'); + +const getAllFiles = (dirPath, arrayOfFiles = []) => { + const files = fs.readdirSync(dirPath); + + files.forEach(function(file) { + if (fs.statSync(dirPath + '/' + file).isDirectory()) { + arrayOfFiles = getAllFiles(dirPath + '/' + file, arrayOfFiles); + } else { + arrayOfFiles.push(path.join(dirPath, file)); + } + }) + + return arrayOfFiles; +} + +module.exports = getAllFiles; diff --git a/helpers/getTotalSize.js b/helpers/getTotalSize.js new file mode 100644 index 0000000..d15d1cb --- /dev/null +++ b/helpers/getTotalSize.js @@ -0,0 +1,16 @@ +const fs = require('fs'); +const getAllFiles = require('./getAllFiles'); + +const getTotalSize = (directoryPath) => { + const arrayOfFiles = getAllFiles(directoryPath); + + let totalSize = 0; + + arrayOfFiles.forEach(function(filePath) { + totalSize += fs.statSync(filePath).size; + }) + + return totalSize; +} + +module.exports = getTotalSize; diff --git a/index.js b/index.js new file mode 100644 index 0000000..9c1dbee --- /dev/null +++ b/index.js @@ -0,0 +1,111 @@ +const fs = require('fs'); +const path = require('path'); +const imagemin = require('imagemin'); +const imageminGifsicle = require('imagemin-gifsicle'); +const imageminMozjpeg = require('imagemin-mozjpeg'); +const imageminPngquant = require('imagemin-pngquant'); +const imageminSvgo = require('imagemin-svgo'); +const imageminWebp = require('imagemin-webp'); +const convertBytes = require('./helpers/convertBytes'); +const getTotalSize = require('./helpers/getTotalSize'); + +const PACKAGE_NAME = 'image-optimist'; +const PROCESSING_TIME = 'Processing time'; + +const imageOptimist = async (config) => { + console.time(PROCESSING_TIME); + console.log(`${PACKAGE_NAME} started`); + + const c = Object.assign({ + sourcePath: null, + destinationPath: null, + mask: '*.{jpg,jpeg,png,svg,gif}', + webp: [ + imageminWebp({ + quality: 90, + method: 4, + metadata: 'none', + }), + ], + plugins: [ + imageminMozjpeg({ + quality: 90, + }), + imageminPngquant({ + speed: 4, + strip: true, + quality: [0.8, 1], + dithering: false, + verbose: true, + }), + imageminSvgo(), + imageminGifsicle({ + optimizationLevel: 3, + }), + ], + }, config); + + const errors = []; + if (c.sourcePath === null) + errors.push('sourcePath is required'); + if (c.destinationPath === null) + errors.push('destinationPath is required'); + if (errors.length !== 0) + console.error(JSON.stringify(errors)); + + const initialDirSize = getTotalSize(c.sourcePath); + + try { + // Collect directory paths + const inputDirectories = [c.sourcePath]; + function throughDirectory(directory) { + fs.readdirSync(directory).forEach(item => { + const absolute = path.join(directory, item); + if (!fs.statSync(absolute).isDirectory()) return; + inputDirectories.push(absolute); + throughDirectory(absolute); + }); + } + throughDirectory(c.sourcePath); + + // Basic processing + const outputDirectories = [c.destinationPath]; + for (const directory of inputDirectories) { + const input = `${directory}/${c.mask}`; + const output = directory.replace(c.sourcePath, c.destinationPath); + const relativePath = '.' + directory.replace(c.sourcePath, ''); + outputDirectories.push(output); + console.log(`Images from ${relativePath} are being processed...`); + await imagemin([input], { + destination: output, + plugins: c.plugins, + }); + } + + // Conversion to webp + if (c.webp) { + for (const directory of outputDirectories) { + const input = `${directory}/*.{jpeg,jpg,png}`; + const relativePath = '.' + directory.replace(c.destinationPath, ''); + console.log(`Images from ${relativePath} are being converted to webp...`); + await imagemin([input], { + destination: directory, + plugins: c.webp, + }); + } + } + } catch (e) { + return console.error(`${PACKAGE_NAME} finished with error:\n`, e); + } + + const finalDirSize = getTotalSize(c.destinationPath); + const diffDirSize = initialDirSize - finalDirSize; + + console.log(`Initial: ${convertBytes(initialDirSize)}`); + console.log(`Final${c.webp ? ' + webp' : ''}: ${convertBytes(finalDirSize)}`); + console.log(`Diff: ${convertBytes(diffDirSize)}`); + console.timeEnd(PROCESSING_TIME); + console.log(`${PACKAGE_NAME} finished`); +}; + +module.exports = imageOptimist; diff --git a/package.json b/package.json new file mode 100644 index 0000000..2a108c4 --- /dev/null +++ b/package.json @@ -0,0 +1,32 @@ +{ + "name": "image-optimist", + "version": "1.0.12", + "description": "A utility for processing and converting images to the requirements of the modern web.", + "private": false, + "main": "index.js", + "author": { + "name": "Aslan Baryshnikov", + "email": "aslanbaryshnikov@gmail.com" + }, + "dependencies": { + "filesize": "^8.0.7", + "imagemin": "7.0.1", + "imagemin-gifsicle": "7.0.0", + "imagemin-mozjpeg": "9.0.0", + "imagemin-pngquant": "9.0.2", + "imagemin-svgo": "9.0.0", + "imagemin-webp": "5.1.0" + }, + "keywords": [ + "image", + "compress", + "processing", + "jpeg", + "jpg", + "png", + "webp", + "gif", + "svg" + ], + "license": "MIT" +}