as-com / mozjpeg-js

Implementation of MozJPEG in pure JavaScript, using Emscripten
https://andrewsun.com/projects/mozjpeg-js/
BSD 3-Clause "New" or "Revised" License
27 stars 6 forks source link

Mozjpeg-js in React Native #4

Open anhnch opened 2 years ago

anhnch commented 2 years ago

Hi, I'm trying to use mozjpeg-js in react native, but I face an issue. React Native doesn't run on node, it doesn't have fs. I have to use an alternative react-native-fs. When reading file, react-native-fs doesn't return binary buffer. It returns a string.

// This function takes a base64-encoded string (the input parameter) and decodes it.
// The return value is in the form of a string containing only characters in the range from U+0000 to U+00FF, 
// each representing a binary byte with values 0x00 to 0xFF.
// The base64.decode() function is designed to be fully compatible with atob() as described in the HTML Standard. 
const content = await RNFS.readFile('path/to/file.jpg', 'base64');

// But mozjpegjs takes binary buffer (correct me!), doesn't it?
const compressed = await mojpegjs.encode(content, { quality: 80 });
// It will cause: Unrecognized input file format --- perhaps you need -targa

Are there anyway to fix this? Please have a look

as-com commented 2 years ago

You should decode the base64 string from react-native-fs into a typed array or ArrayBuffer before passing it to this library. This library may work for you: https://github.com/superhuman/fast64

Alternatively, use a filesystem library that allows for reading files into typed arrays or ArrayBuffers.

hirbod commented 2 years ago

I would use this JSI lib instead:

https://github.com/mrousavy/react-native-blob-jsi-helper