What is the code to transform an image (maximum of 200 KB) into a Base64 String?
I need to know how to do it with Android, because I have to add the functionali
If you're doing this on Android, here's a helper copied from the React Native codebase:
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;
// You probably don't want to do this with large files
// (will allocate a large string and can cause an OOM crash).
private String readFileAsBase64String(String path) {
try {
InputStream is = new FileInputStream(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
byte[] buffer = new byte[8192];
int bytesRead;
try {
while ((bytesRead = is.read(buffer)) > -1) {
b64os.write(buffer, 0, bytesRead);
}
return baos.toString();
} catch (IOException e) {
Log.e(TAG, "Cannot read file " + path, e);
// Or throw if you prefer
return "";
} finally {
closeQuietly(is);
closeQuietly(b64os); // This also closes baos
}
} catch (FileNotFoundException e) {
Log.e(TAG, "File not found " + path, e);
// Or throw if you prefer
return "";
}
}
private static void closeQuietly(Closeable closeable) {
try {
closeable.close();
} catch (IOException e) {
}
}