js代码
import sharp from 'sharp';
import fs from 'fs';
// Input and output file paths
const inputFilePath = 'input.jpg';
const outputFilePath = 'output.webp';
// Create a readable stream from the input file
const readableStream = fs.createReadStream(inputFilePath);
// Create a writable stream to the output file
const writableStream = fs.createWriteStream(outputFilePath);
// Create a Sharp instance for image processing
const imageProcessing = sharp();
// Configure the image processing operations
imageProcessing.webp();
// Pipe the readable stream through the image processing and then to the writable stream
readableStream.pipe(imageProcessing).pipe(writableStream);
// Handle the completion of the piping process
writableStream.on('finish', () => {
console.log('Image processing completed!');
});
缺点
- 长度和宽度不能超过4096,否则会报错
- 转换某些图片的时候会报错,不清楚原因