wasabeef / richeditor-android

RichEditor for Android is a beautiful Rich Text WYSIWYG Editor for Android.
Apache License 2.0
6.22k stars 1.2k forks source link

Display an image in the RichEditor with an Intent #289

Closed Clement-Cauet closed 1 year ago

Clement-Cauet commented 1 year ago

Hello, I can't choose an image in my local storage, display the image in my RichEditor and stock the image in my database (I stock my html in my database) in same time. I work with android 11 API 30. My AndroidManifest.xml containt this lines : <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

If I use this line : instanceFragment.getRichEditor().insertImage("https://raw.githubusercontent.com/wasabeef/art/master/chip.jpg", "image", 300); The image is display in the RichEditor and I can stock in my database but I have don't choose my image in my local storage.

If I use this line : instanceFragment.getRichEditor().insertImage("File://" + destination.getPath(), "image", 300); The image isn't display in the RichEditor (the alt is display) but I can stock in my database and I have choose my image in my local storage.

If I use this line : instanceFragment.getRichEditor().insertImage(url, "image", 300); The image is display in the RichEditor and I have choose my image in my local storage but I can't stock in my database (because this is a temp url).

This is my code : RichEditor.txt

Can you help me please ? Thank in advance.

Clement-Cauet commented 1 year ago

Hello, I found a solution to insert an image from the phone's internal storage to the RichEditor, you can encode the image in base64. This allows you to store the image in a database and to bypass the various security features of Android and HTML. Here is the code to do this:

//- Create image file in local storage
File destination = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "image.jpg");

//- Encoding image in base64
byte[] imageBytes = new byte[0];
try {
      imageBytes = Files.toByteArray(new File(destination.getPath()));
      String imageBase64 = BaseEncoding.base64().encode(imageBytes);
      instanceFragment.getRichEditor().insertImage("data:image/jpg;base64," + imageBase64, destination.getName(), 100);
} catch (IOException e) {
      throw new RuntimeException(e);
}

Don't forget to format the file type, in the example I use a jpg format, but you could use another format like a png format.