there's a good post here:
https://www.b4x.com/android/forum/threads/externalstorage-access-sd-cards-and-usb-sticks.90238/
about accessing the sdcard. comes with a class module to facilitate things.
if you're thinking of writing to external storage on the device, you'll need a runtime permission.
see here:
https://www.b4x.com/android/forum/threads/runtime-permissions-android-6-0-permissions.67689/
you add a couple lines to the manifest and to the app. clear and easy.
by gallery, i assume you mean the usual DCIM/Camera folder. if you're thinking about trying to write to another app's internal folder, that's a different story. for that, you'd need to use an intent to share with fileprovider (assuming the other app can accept shared files):
https://www.b4x.com/android/forum/threads/sharing-files-from-your-app-with-file-provider.70458/
you might want to think about separating these actions from your referenced sub and, perhaps, from each other by passing the bitmap (or possibly saving it locally first)