[英]how to pass a buffer to imagemin module in node.js?
在舊版本的 imagemin 中,我能夠向模塊傳遞一個緩沖區,如下所示:
new ImageMinify()
.src(StreamOrBuffer)
.use(ImageMinify.jpegtran({progressive: true}))
在當前版本的 imagemin 中沒有src函數,調用該模塊將產生一個承諾。
我找不到如何在較新版本的 imagemin 中實現相同的結果
是否可以完成或移除支持?
我從 github 倉庫得到了答案。 我在這里發布答案,以防其他人遇到同樣的問題:
您可以使用imagemin.buffer提供緩沖區。 Streams 從未被支持。
這是一個函數:
- 使用銳利在給定尺寸內調整圖像大小
- 使用帶緩沖區的 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)
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.