I am trying to resize an image after streaming from google cloud storage. The streaming works fine but the resizing does not seem to work. I need to pass the image object to the resize function of sharpjs which will then resize and return the image in the API response.
My code is as below:
const express = require('express')
const {Storage} = require('@google-cloud/storage');
let server = express()
const storage = new Storage();
const bucketName = '<some-bucket-name>'
server.get('/*', async (req, res, next) => {
// Extract the query-parameter
const widthString = req.query.width
const heightString = req.query.height
const format = req.query.format
const fileName = req.path.substring(1);
console.log("url: ", req.path)
// Parse to integer if possible
let width, height
if (widthString) {
width = parseInt(widthString)
}
if (heightString) {
height = parseInt(heightString)
}
// Set the content-type of the response
res.type(`image/${format || 'png'}`)
// Get the resized image
downloadFileStream(fileName).then((imageObj) =>{
resize(imageObj, format, width, height).pipe(res)
})
.catch ((e) =>
console.log(e)
);
})
async function downloadFileStream(fileName){
return await storage.bucket(bucketName).file(fileName).createReadStream().pipe()
}
I am missing something in the way i should be calling resize after the file download. I get following error:
TypeError: Cannot read property 'on' of undefined
at PassThrough.Readable.pipe (internal/streams/readable.js:657:8)
at streamFile (/home/adityam/imageoptimizer/server.js:40:82)
at /home/adityam/imageoptimizer/server.js:30:7
Based on this and this tutorials, I would suggest rewriting your resize function in this way:
include sharp library
const sharp = require("sharp");
get image using downloadFileStream function, then resize
const image = downloadFileStream(fileName)
const resized = await sharp(image)
.resize({
width: width,
height: height
})
.toBuffer()
.then( data => {
//...
})
See also: