Skip to content

Instantly share code, notes, and snippets.

@kamal-hossain
Created September 23, 2021 10:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kamal-hossain/5b50b01ac141301cebbaf3ce424b9ec9 to your computer and use it in GitHub Desktop.
Save kamal-hossain/5b50b01ac141301cebbaf3ce424b9ec9 to your computer and use it in GitHub Desktop.
Image download, crop and convert to base64 in Nodejs
const express = require('express')
const imageToBase64 = require('image-to-base64')
const app = express()
const fs = require('fs')
const Axios = require('axios')
const sharp = require('sharp')
app.use(express.json())
app.use((r, res, next) => {
console.log(r.url)
next()
})
async function downloadImage(url, filepath) {
const response = await Axios({
url,
method: 'GET',
responseType: 'stream',
})
return new Promise((resolve, reject) => {
response.data
.pipe(fs.createWriteStream(filepath))
.on('error', reject)
.once('close', () => resolve(filepath))
})
}
app.get('/', async (req, res) => {
// Download the given PDF
await downloadImage(
`https://zercon.tapcom.com/manage/invoice/149222/print/image/6ba2a8c8-19e4-4192-962e-9cc63a52c2aa/`,
'downloaded.png'
)
// Crop the extra area of the image
await sharp('./downloaded.png')
// .resize({ height: 100 })
// .png()
.extract({ left: 0, top: 0, width: 630, height: 2200 })
.toFile('output.png', function (err) {
// output.jpg is a 300 pixels wide and 200 pixels high image
// containing a scaled and cropped version of input.jpg
console.log(err)
if (!err) {
imageToBase64('output.png') // Image URL
.then((response) => {
// console.log(response) // "iVBORw0KGgoAAAANSwCAIA..."
res.status(200).json({
message: response,
})
})
.catch((error) => {
console.log(error) // Logs an error if there was one
})
}
})
})
app.post('/', (req, res) => {
console.log(req.body)
res.status(200).json({
message: 'Watch request body on server console.log()',
})
})
app.listen(3000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment