Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display png image from native module in react native

I have a slider component which I want to have a handle as png image pass as a prop. Now, I want that png image to pass through react native to native modules(android and ios both). The component is written at native side for both ios(Objective C) and android(Java).

  1. How can I pass png image as a prop to native modules?
  2. How can I use them at native Java part?(I am using Canvas to draw my slider as shown below).
  3. How can I use them at native Objective C?(I am using CGContext to draw my slider).

What I have tried:

  1. I resolved path of png image by following code at React Native side.
  const myImage = require('../assets/slider-handle.png');
  const resolveAssetSource = require('react-native/Libraries/Image/resolveAssetSource');
  const resolvedImage = resolveAssetSource(myImage); 

Then pass the path of image as a prop imagePath={resolvedImage.uri}.

Then at Java part I do following:

public void drawImage(String imagePath, Canvas canvas, int x, int y) {
     Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
     canvas.drawBitmap(bitmap, y, x, somePaintValue);
}

I am getting the path of image(the path is something like this: (http:/10.0.2.2:8081/assets/app/components/slider/assets/slider.png), I have verified that at native side by consoling the path.

Not sure if I need to pass only path of image or maybe there is a way to pass whole png. This is my first time working with Java and Objective C. This is the slider I am developing. Any help will be really appreciated.

like image 256
Sourav Yadav Avatar asked Jul 03 '26 19:07

Sourav Yadav


1 Answers

I see that the thread is quite old, but this can be useful in the future.

A way that works for me is encoding the bitmap to Base64.

Java Side:

iconBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);

React-native side:

   <Image source={{uri: `data:image/png;base64,${props.item.iconBase64}`}}/>

If needed you can even compress the image:

bitmap.compress(Bitmap.CompressFormat.PNG, 10, byteArrayOutputStream);
like image 72
Valentin Kisimov Avatar answered Jul 06 '26 07:07

Valentin Kisimov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!