从谷歌云存储流式传输后使用sharp调整图像大小



我正在尝试从谷歌云存储流后调整图像的大小。流式工作良好,但调整大小似乎不工作。我需要将图像对象传递给sharpjs的resize函数,然后在API响应中调整大小并返回图像。

我的代码如下:

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()
}

我在文件下载后应该调用调整大小的方式中缺少了一些东西。我得到以下错误:

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

基于这个和这个教程,我建议这样重写你的resize函数:

include sharp library

const sharp =  require("sharp");

使用downloadFileStream函数获取图像,然后调整

const image = downloadFileStream(fileName)
const resized = await sharp(image)
.resize({
width: width,
height: height
})
.toBuffer()
.then( data => {
//...
})

参见:

  • https://github.com/lovell/sharp

相关内容

  • 没有找到相关文章

最新更新