react-native中的图像压缩

Bad*_*dri 6 javascript android image-compression react-native mozjpeg

当我根据它工作正常的文档在 node.js 中实现它时,我试图用mozjpeg压缩图像。

const input = fs.readFileSync("in.ppm");
const out = mozjpeg.encode(input, { quality: 85 });
Run Code Online (Sandbox Code Playgroud)

我需要在客户端进行压缩,所以我尝试对 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);
Run Code Online (Sandbox Code Playgroud)

客户端实现

fs.readFile(image.path).then(data => {
    const out = mozjpeg.encode(data, { quality: 85 });
    console.log(out);
}
Run Code Online (Sandbox Code Playgroud)

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

  • 尝试以十六进制、缓冲区、base64 和普通 URL 字符串提供输入。
  • 由于 Android URL 包含file://前缀,我也尝试删除它们。

Moh*_*sen 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;
}
Run Code Online (Sandbox Code Playgroud)