6

当我根据运行良好的文档在 node.js 中实现它时,我正在尝试使用mozjpeg压缩图像。

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);
}

这是我尝试过的事情的清单

  • 尝试以十六进制、缓冲区、base64 和纯 URL 字符串形式输入。
  • 由于 Android URL 包含file://前缀,因此我也尝试将其删除。
4

3 回答 3

2

其实我不知道,mozjpeg但我更喜欢在问题环境中使用纯 JavaScript 方式来解决我的问题。

我猜你的想法落在了单向 bios 中,离开 NodeJS 解决方案,你在 react-native 环境中,所以使用React Native Compress ImageReact 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.

});
于 2020-03-16T05:18:36.343 回答
2

此外,还有另一个很好的 React-Native 图像裁剪选择器库,其目的是抓取一些图像并裁剪它们,但它具有很好的压缩能力。也许这个库有一个很好的压缩算法,比如mozjpeg

它可以打开相机、打开图库或使用恒定图像,甚至可以关闭裁剪:

ImagePicker.openCamera({
  width: 300,
  height: 400,
  compressImageQuality: 0.2
}).then(image => {
  // do what you want
}).catch(e => {
  // handle error
});

好配置,它有很多调整选项。我希望它对你有帮助。

于 2020-03-16T12:31:00.637 回答
1

您可以在mozjpeg-js文档中找到输入参数是:

类型化数组或数据缓冲区


fs.readFile客户端 ( react-native-fs) 中的返回类型是Promise<string>和返回内容。(文档

但在服务器端(fs),fs.readFileSync返回缓冲区对象。(文档


因此,您可以使用此函数将字符串更改为类型化数组:

function str2ta(str) {
  var bufView = new Uint16Array(str.length*2); // 2 bytes for each char
  for (var i=0, strLen=str.length; i<strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return bufView;
}
于 2020-03-09T06:56:44.263 回答