I need to convert an image choosen from the gallery into a base64 string. Then, I pass the baase64 string as a parameter for an API request. There is only one problem. When I use netbeans it works, when I use Android Studio it doesn't. I found that the problem is the base64 string output. I don't know why, if I use the same exactly image, the output is different. Maybe the problem happpens because I have to use the same exact method to read the image file...?
That's my code in Netbeans(working):
InputStream inputStream = new FileInputStream("testImage.jpg");
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
String encodedFile = Base64.getEncoder().encodeToString(bytes);
And that's the code in Android Studio:
Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageData = baos.toByteArray();
InputStream inputStream = getContentResolver().openInputStream(imageUri);
byte[] buffer_new = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer_new)) != -1) {
output.write(buffer_new, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
String encodedImage = Base64.encodeToString(bytes,Base64.DEFAULT);
Log.v("encodedImage", encodedImage);
The ouput string are almost the same only at the first char..then they are different..with the android studio encoded string, I get this error when I try to use the API.
BAD_ARGUMENTS:<key>
Error while parsing some arguments. This error may be caused by illegal type or length of argument.
What should I use to get the same base64 string? ps. in Netbeans the image is a file in the same folder of the project, in android studio the user can load a picture from gallery.