我正在尝试使用 mozjpeg 压缩图像当我根据文档在 node.js 中实现它时,它运行良好。
const input = fs.readFileSync("in.ppm");
const out = mozjpeg.encode(input, { quality: 85 });
我需要在客户端做压缩,所以我尝试对 react-native 做同样的事情,因为 react-native 不包含 fs 等核心节点模块,我需要去第三方库 react-native-fs用于文件读取。
当我试图执行
mozjpeg.encode(input, { quality: 85 });
在 react-native 中它会抛出 Unrecognized input file format --- perhaps you need -targa
服务器端实现
const mozjpeg = require("mozjpeg-js");
const fs = require("fs");
const input = fs.readFileSync(filePath);
const out = mozjpeg.encode(input, { quality: 85 });
console.error(out.stderr);
fs.writeFileSync("out.jpg", out.data);
客户端实现
fs.readFile(image.path).then(data => {
const out = mozjpeg.encode(data, { quality: 85 });
console.log(out);
}
这是我尝试过的事情的 list
file://
作为前缀,我也尝试删除它们。 最佳答案
其实我不知道mozjpeg
但我更喜欢在问题环境上使用纯 JavaScript 的方式来解决我的问题。
我猜你的想法落在了单向 bios 中,离开 NodeJS 解决方案,你在 react-native 环境中,所以使用 React Native Compress Image或 React Native Image Resizer .
根据我的经验,我更喜欢使用第二个,React Native Image Resizer .
安装后,使用如下:
ImageResizer.createResizedImage(
imageUri,
newWidth,
newHeight,
compressFormat,
quality
)
.then( resizedImageUri => {
// the resizedImageUri is accessible here to use.
}).catch( err => {
// Catch any error here.
});
关于javascript - react-native 中的图像压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60566603/