javascript - react-native 中的图像压缩

标签 javascript android react-native image-compression mozjpeg

我正在尝试使用 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
  • 尝试以十六进制、缓冲区、base64 和纯 URL 字符串形式输入。
  • 由于 Android URL 包含 file://作为前缀,我也尝试删除它们。
  • 最佳答案

    其实我不知道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.
    
    });
    

    关于javascript - react-native 中的图像压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60566603/

    相关文章:

    javascript - 如何使用 .className 显示每个 div 的第一张图片?

    android - Unity 与 Eclipse 的集成

    android - OrmLite java.lang.IllegalStateException : you must call initialize() before you can use the dao

    javascript - 需要在 react 导航中设置默认 Prop

    javascript - XML 保存到文件 Javascript asp

    Javascript-Array 从一行到另一行返回不同的值。但为什么? (懒惰的控制台+我的小 bug )

    java - Android 以编程方式强制关闭处理

    typescript - 如何在 React Navigation 5 和 TypeScript 中键入 Tab Navigator

    cookies - react 本地获取Cookie

    javascript - 数据仅在警报后可用