Convert static image to Base64 in ReactNative - android

I have static image which i need to convert in Base64 and then send it to Android/iOS native code.
If i select an image from file i am able to send it to native code and convert that to Base64.
But what if i have static image and then send it to native code.
<Image source={require('./img/icon.png')}/>
I want icon.png to be sent in Android/iOS native module.
I have done native coding, it is something like this
#ReactMethod
public void filterBase64(String base64, Callback stringCallback) {
}
But stucked at how to send Base64
I have checked react-native-image-to-base64 but not able to get solution, when i use
NativeModules.RNImageToBase64.getBase64String(uri, (err, base64) => {
// Do something with the base64 string
})
It shows error undefined is not an object

With the help of RNFS plugin you can access React Native assets and convert them to Base64.
var RNFS = require('react-native-fs')
base64data = await RNFS.readFile('./img/icon.png', 'base64').then();
console.log(base64data);

Related

How convert base64 to pdf React-Native

I created an app using react-native and have some base64 data from
api. I want convert base64 data to pdf format. if you have any idea
please help me. thanks.
You can use react-native-pdf package (https://www.npmjs.com/package/react-native-pdf). If you want to show the pdf in your app , this package would be quite helpful as it supports loading PDFs from base64 string for both ios and android . You can specify the pdf's source from your base64 data as shown in their example :
{uri:"data:application/pdf;base64,JVBERi0xLjcKJc..."}
I'm assuming, converting to PDF as in saving the base64 format data as PDF in some file.
the following code can help you do the same,
let fPath = Platform.select({
ios: fs.dirs.DocumentDir,
android: fs.dirs.DownloadDir,
});
fPath = `${fPath}/pdfFileName.pdf`;
if (Platform.OS === PlatformTypes.IOS) {
await fs.createFile(fPath, base64Data, "base64");
} else {
await fs.writeFile(fPath, base64Data, "base64");
}
// RNFetchBlob can be used to open the file

Uploading Audio to Cloudinary

this is my first Stack Overflow post so please go easy on me!
I'm building an audio recording app using EXPO as the SDK with React Native. One of the main features of the app is to be able to to record live audio as well as uploading audio from the client's device. By leveraging Expo's Audio API and FileSystem, I'm successfully able to record and save live audio and then retrieve it via FileSystem to upload, however I'm running in an error when I try to pass the localUri to upload to my Cloudinary database. There is very little documentation in regards to audio and audio uploads to cloudinary are clumped into video uploads so there's nothing audio specific to really point me in the right direction. I've tried converting the URI to base64 as well as a variety of MIME types but the response from Cloudinary with a secure url returns empty/undefined. I've successfully uploaded images with this method so you can imagine how frustrating it is. Here's my code that grabs a recording and tries to upload it to Cloudinary:
DocumentPicker.getDocumentAsync({
type: '*/*',
copyToCacheDirectory: true,
base64: true
})
.then(succ => {
//check out the saved info
console.log(succ, `path: ${succ.uri}, type: ${succ.type}, name: ${succ.id}, size: ${succ.size}`)
let Base64 = {/* Truncated Base64 object*/};
let base64Aud = `data:audio/x-wav;base64, ${Base64.encode(succ.uri)}`;
let cloud = `https://api.cloudinary.com/v1_1/${CLOUD_NAME}/upload`;
const data = {
'file': base64Aud,
'upload_preset': CLOUDINARY_UPLOAD_PRESET,
'resource_type': 'video',
}
fetch(cloud, {
body: JSON.stringify(data),
headers: {
'content-type': 'application/x-www-form-urlencoded'
},
method: 'POST',
})
.then(async r => {
let data = await r.json()
console.log('cloudinary url:', data.secure_url)
return data.secure_url
})
.catch(err => console.log(err))
}
This call prints the following to the console:
Object {
"name": "20200117_143416.mp4",
"size": 519612343,
"type": "success",
"uri": "file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Faloud-aaf24bff-8000-47f0-9d1c-0893b81c3cbc/DocumentPicker/c922deb7-fd4f-42d9-9c28-d4f1b4990a4c.mp4",
} path: file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540anonymous%252Faloud-aaf24bff-8000-47f0-9d1c-0893b81c3cbc/DocumentPicker/c922deb7-fd4f-42d9-9c28-d4f1b4990a4c.mp4, type: success, name: undefined, size: 519612343
data:audio/x-wav;base64, ZmlsZTovLy9kYXRhL3VzZXIvMC9ob3N0LmV4cC5leHBvbmVudC9jYWNoZS9FeHBlcmllbmNlRGF0YS8lMjU0MGFub255bW91cyUyNTJGYWxvdWQtYWFmMjRiZmYtODAwMC00N2YwLTlkMWMtMDg5M2I4MWMzY2JjL0RvY3VtZW50UGlja2VyL2M5MjJkZWI3LWZkNGYtNDJkOS05YzI4LWQ0ZjFiNDk5MGE0Yy5tcDQ=
cloudinary url: undefined
Does anyone see any glaring issues or have any insight on this issue? Better yet, successfully uploaded audio to Cloudinary from the client using Expo & React Native? Thanks!
While I can't say for certain why the uploads fail in your case without seeing the error returned by Cloudinary, I have created a working JSFiddle which you can use to upload a Base64 data URI encoded audio file (1-second audio in my example to keep it short). Just replace your cloud name in the API endpoint URL and set the upload preset. Once that uploads successfully in your account you can replace the example with your Base64 Data URI and see if it works or not. That will tell you if the issue is with the Base64 String itself. Having said that, sharing the error returned by Cloudinary would be the best indicator.
Example code below:
var fd = new FormData();
fd.append("file", "data:audio/mpeg;base64,SUQzBAAAAAABBFRYWFgAAAASAAADbWFqb3JfYnJhbmQ...");
fd.append("upload_preset", "");
fd.append("resource_type", "video")
fetch('https://api.cloudinary.com/v1_1/cloud_name_here/upload',
{
method: 'POST',
body: fd
}
);

How to upload an image from Odoo 11 to an Android application?

I use XML-RPC to upload images from Odoo-11 to to an android application.
How can I convert the result of a request to a bytes array bytes[]?
Because in the table the format of the field image is bytes[].
You will need to code and decode the image file data as base64 to send and receive the data properly
In Odoo The image files are storing as string (base64) , i think you need to read the image data from odoo to mobile application for displaying in mobile application right ?
you can use the XML-RPC library Odoo External Api
The External API is using For integrate the odoo with other Systems
Check The url , there we have "Search_read" method to read data from odoo
you will get base64 string and then you need to convert the base64 string in your mobile application to display the image
eg : models.execute_kw('res.partner','search_read',[['id','=',1]],{'fields':['name','image']})
you will get the name and profile photo of partner id 1
I there any possibility to use one of the image loading library (glide,picasso.etc) in an odoo mobile framework?
You can just create below function into your activity/fragment.
public static String encodeBitmapToString(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream.toByteArray();
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
return encoded;
}

Django REST Framework: sending an image from android

I'm trying to send an image through my Android application to Django, where it will make the analysis of that image (with python code). I'm sending the image in Base64, but when I receive it, the format gets all messed up. How can I send the image correctly, and is this the right format?
Have you tried using this?
link
combined with a code like that:
class UploadedImageSerializer(serializers.ModelSerializer):
"""
Serializer for the UPloadedImage Model
Provides the pk, image, thumbnail, title and description
"""
class Meta:
model = UploadedImage
fields = ('pk', 'image', 'thumbnail', 'title', 'description', )
read_only_fields = ('thumbnail',)

How can I retrieve a file from the file system using React Native, for conversion to base64 and http posting as JSON?

I am using the react native template from this article. The code is all available on Github here.
You can use the app to record audio and save to the file system. I figured out how to retrieve the file URIs, but I'm finding it impossible to get the actual contents of the file itself. All I want to do is retrieve the actual file contents as a binary or ascii or hex string or whatever (it's a .m4a file), so I can convert it to base64 encoding and then post it as JSON to my server. Here's what my code looks like:
/src/screens/RecordAudioScreen/RecordAudioScreenContainer.js
onEndRecording: props => async () => {
try {
// here is the URI
console.log("HERE IS THE URI!!");
const audio_data = "URI: " + props.recording._uri;
// Help needed here
// retrieve file contents from the Android/iOS file system
// Encode as base64
audio_data = ... // ???????
// this works already, posts to the server
fetch("https://myserver.com/accept_file",
{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: "POST",
body: JSON.stringify({user_id: 1, audio_data: audio_data})
})
.then(function(res){ console.log(res) })
.catch(function(res){ console.log(res) });
console.log("FINISHED POST REQUEST!!!")
await props.recording.stopAndUnloadAsync();
await props.setAudioMode({ allowsRecordingIOS: false });
} catch (error) {
console.log(error); // eslint-disable-line
}
if (props.recording) {
const fileUrl = props.recording.getURI();
props.recording.setOnRecordingStatusUpdate(null);
props.setState({ recording: null, fileUrl });
}
},
I've already tried a bunch of stuff with no success. Ideally I just get the file contents from the File system, convert to base64 and post it off all in this method just in javascript, but this is seemingly very difficult for what should be a pretty standard thing to do in an app based framework.
Here's some stack overflow questions on React Native Fetch Blob which I couldn't make work Fetch Blob 1 Fetch Blob 2
I've tried using React Native Fs, but I can't get it to load properly, I got super bogged down in stuff I didn't understand after trying to eject the app. I'd prefer a plain React Native solution if possible.
I've also tried some code using FormData but couldn't get that to work either.
Maybe the answer is kind of like this question about retrieving images from firebase? I don't know, this is my first attempt at doing anything in React.
It might also have something to do with the "file://" prefix in the URI that gets generated because there's a lot of questions discussing removing that (only for Android, or only for iOS I'm not too clear).
Converting to base64 will be done with something like this, but I need the actual file contents first:
Very appreciative of any help.
Some time ago I wrote a simple example of a record voice app.
To get the files I used this method:
import RNFS from 'react-native-fs';
(...)
getFiles() {
RNFS.readDir(AudioUtils.DocumentDirectoryPath)
.then((result) => {
this.setState({recordedFiles: result});
return Promise.all([RNFS.stat(result[0].path), result[0].path]);
})
.catch((err) => {
console.log(err.message, err.code);
});
}
It worked just fine.
Here's the full example https://github.com/soutot/react-native-voice-record-app
Let me know if it helped. Otherwise we can try a different approach

Categories

Resources