Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image compression in react-native

I am trying to compress images with mozjpeg when I implemented it in node.js according to the docs it worked fine.

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

I need to do the compression on the client-side, so I tried to do the same with react-native since react-native doesn't contain core node modules such as fs, I need to go for a third party library react-native-fs for file reading.

When I tried to execute mozjpeg.encode(input, { quality: 85 }); in react-native it throws Unrecognized input file format --- perhaps you need -targa

server-side implementation

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

client-side implementation

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

Here is the list of thing I tried

  • Tried giving input in hex, buffer, base64 and plain URL string.
  • Since the Android URL contains file:// as prefix I tried to remove them also.
like image 802
Badri Avatar asked Mar 06 '20 14:03

Badri


1 Answers

Actually I don't know about mozjpeg but I prefer to use pure JavaScript way on the environment of problem to solve my problem.

I guess your thought fell in one-way bios, leave away the NodeJS solution, you are in the react-native environment so use React Native Compress Image or React Native Image Resizer.

Based on my experiences I prefer to use the second one, the React Native Image Resizer.

After install, use it like below:

ImageResizer.createResizedImage(
  imageUri,
  newWidth,
  newHeight,
  compressFormat,
  quality
)
  .then( resizedImageUri => {

    // the resizedImageUri is accessible here to use.

  }).catch( err => {

  // Catch any error here.

});
like image 103
AmerllicA Avatar answered Oct 11 '22 13:10

AmerllicA