node.js把webp,gif格式图片转换成jpg格式图片
苹果手机及苹果电脑无法识别安卓的webp格式图片
,安卓手机无法识别苹果的.livp(实况图)和.HEIC格式图片(老系统的苹果手机实况图)。
可以通过sharp把webp和gif格式图片转换成jpg格式图片,质量0.8。
const sharp = require('sharp');
ImageTool.convertToJpeg = async function(inputPath, quality = 80) {const fileExt = path.extname(inputPath).toLowerCase();const outputPath = inputPath.replace(fileExt, '.jpg');try {// 其他格式使用 sharpawait sharp(inputPath).jpeg({ quality: quality,chromaSubsampling: '4:4:4'}).toFile(outputPath);return outputPath;} catch (error) {console.error('图片转换失败:', error);// throw error;throw msgCode[39522]('上传');}
};
调用代码:
// 获取文件扩展名const fileExt = path.extname(ctx.req.file.originalname).toLowerCase();let convertedPath = null; // 不支持的格式,转换为 JPEGconst convertedPath = await ImageTool.convertToJpeg(ctx.req.file.path, 80);const readStream = fs.createReadStream(convertedPath);let arr = ctx.req.file.path.split('/');let filename = '/img/' + arr[arr.length - 1].replace(fileExt, '.jpg');//上传阿里云图片接口。return ImageTool.uploadImage(filename, fileExt, readStream, convertedPath, ctx.req.file.path);
图片上传阿里云。