在旧版本的imagemin中,我能够将模块传递给像这样的缓冲区:
new ImageMinify()
.src(StreamOrBuffer)
.use(ImageMinify.jpegtran({progressive: true}))
在当前版本的imagemin中没有 src 函数,调用该模块将产生一个承诺。
我找不到如何在较新版本的imagemin中获得相同的结果
是否可以完成或支持已被删除?
答案 0 :(得分:1)
我从github回购中得到了答案。我在这里发布答案,以防其他人遇到同样的问题:
您可以使用imagemin.buffer提供缓冲区。 Streams从未受到支持。
答案 1 :(得分:0)
以下是一个函数:
-使用锐利的图像调整给定尺寸的图像
-使用带缓冲区的imagemin压缩图像(它将流转换为缓冲区以进行压缩)
-保存缓冲区
我没有找到使imagemin与带样式的流兼容的好方法,因此它使用临时可写流存储缓冲区。
/**
* It:
* 1. Resize the image directly from a GCP read stream to a 500x500 keeping the aspect ratio
* 2. Create a temp Writable stream to transform it to buffer
* 3. Compress the image using 'imagemin'
* 4. Save it to GCP back
* 5. Delete original image
*
* @param filePath
* @param width
* @param height
*/
const resize = async (
bucket: Bucket,
filePath: string,
width: number,
height: number
): Promise<[File, string]> => {
const ext = path.extname(filePath)
const fileName = path.basename(filePath, ext)
const [imageMetadata] = await bucket.file(filePath).getMetadata()
const metadata = {
contentType: imageMetadata.contentType,
predefinedAcl: 'publicRead',
}
const newFileName = `${fileName}_${width}x${height}${ext}`
const thumbFilePath = path.join(path.dirname(filePath), newFileName)
const outputFile = bucket.file(thumbFilePath)
const bufferData: any[] = []
const tempWritableStream = new stream.Writable()
tempWritableStream._write = function(chunk, encoding, done) {
bufferData.push(chunk)
done()
}
const pipeline = sharp()
bucket
.file(filePath)
.createReadStream()
.pipe(pipeline)
pipeline
.resize(width, height, { fit: 'inside' })
.jpeg({ progressive: true, force: false })
.png({ progressive: true, force: false })
.pipe(tempWritableStream)
return await new Promise((resolve, reject) =>
tempWritableStream
.on('finish', async () => {
const transformedBuffer = await minimizeImageFromBufferArray(
bufferData
)
await saveImage(transformedBuffer, outputFile, metadata)
await bucket.file(filePath).delete()
resolve([outputFile, newFileName])
})
.on('error', reject)
)
}