In older version of imagemin I was able to pass the module a buffer like so:
new ImageMinify()
.src(StreamOrBuffer)
.use(ImageMinify.jpegtran({progressive: true}))
In the current version of imagemin there is no src function and calling the module will result in a promise.
I could not find how to achieve the same result in newer version of imagemin
Could it be done or that the support was removed?
I got an answer from the github repo. I'm posting the answer here in case someone else will encounter the same problem:
You can supply a buffer using imagemin.buffer . Streams has never been supported.
Here is a function that:
- resize an image within given sizes using sharp
- use imagemin with buffer to compress the image (it convert the stream to a buffer to do so)
- save the buffer
I did not find a good way to make imagemin compatible with stream with style, so it use a temp writable stream to store the buffer.
/**
* 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)
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.