Last active
November 23, 2022 23:45
-
-
Save fob2257/9bd68fa966f369fd25ac467e68fdc854 to your computer and use it in GitHub Desktop.
Made this with the intention of resizing & saving img url's
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
const path = require('path'); | |
const fs = require('fs'); | |
const Jimp = require('jimp'); | |
const { v4: uuidv4 } = require('uuid'); | |
const imagesDirPath = path.join(__dirname, './images/'); | |
const writeFile = (dirPath, fileName, data, options) => { | |
if (!fs.existsSync(dirPath)) fs.mkdirSync(dirPath); | |
const joinedPath = path.join(dirPath, fileName); | |
return new Promise((resolve, reject) => | |
fs.writeFile(joinedPath, data, options, (error) => { | |
if (error) { | |
return reject(error); | |
} | |
resolve(joinedPath); | |
}) | |
); | |
}; | |
const clipImage = async (imagePath, saveImage = true) => { | |
const jimpImage = await Jimp.read(imagePath); | |
const contentType = jimpImage._originalMime; | |
const fileName = `${uuidv4()}.${contentType.split('/')[1]}`; | |
const regex = /^data:([A-Za-z-+/]+);base64,(.+)$/; | |
const newImage = await jimpImage | |
.resize(135, 200) | |
.quality(60) | |
.getBase64Async(contentType) | |
.then((value) => | |
Promise.resolve({ | |
base64: { | |
value, | |
matches: value.match(regex) | |
} | |
}) | |
); | |
newImage.buffer = new Buffer.from(newImage.base64.matches[2], 'base64'); | |
newImage.path = saveImage | |
? await writeFile(imagesDirPath, fileName, newImage.base64.matches[2], { | |
encoding: 'base64' | |
}) | |
: null; | |
return newImage; | |
}; | |
clipImage('path | url', false).then((clippedImage) => | |
console.log(clippedImage) | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment