Get base64 String from Image URI - java

I have content:// URI of an image and I want to convert it to base64. I don't know how to do this.
Here is my code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==123 && resultCode==RESULT_OK) {
Uri selectedfile = data.getData(); //The uri with the location of the file
if (selectedfile != null) {
Log.e("image", selectedfile.toString());
}
}
}

You can do it by using 2 steps.
1- URI to Bitmap conversion:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==123 && resultCode==RESULT_OK) {
Uri selectedfile = data.getData(); //The uri with the location of the file
if (selectedfile != null) {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedfile);
}
}
}
2- Bitmap to Base64 String conversion:
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] byteArray = outputStream.toByteArray();
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
As a result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==123 && resultCode==RESULT_OK) {
Uri selectedfile = data.getData(); //The uri with the location of the file
if (selectedfile != null) {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedfile);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
byte[] byteArray = outputStream.toByteArray();
//Use your Base64 String as you wish
String encodedString = Base64.encodeToString(byteArray, Base64.DEFAULT);
}
}
}

Related

Resgistering photos issues in android programming

I am implementing an android app using camera to take pictures then registering it in External_storage\Android\data\com.abc.projectname.bf . But after openning the camera , even if i don't capture , an image file is registered in the directory . How can i solve that , here is the code :
public void onCapturePhoto(String fileName){
//Intent to take photos
File storageDirectory = requireActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
Log.d("#picName",fileName);
File imageFile = File.createTempFile(fileName,".jpg",storageDirectory);
currentPhotoPath = imageFile.getAbsolutePath();
Uri imageUri= FileProvider.getUriForFile(requireActivity(),"com.ticanalyse.mheath.bf",imageFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
startActivityForResult(intent,1);
Log.d("#image_length is ",String.valueOf(imageFile.length()));
} catch (IOException e) {
e.printStackTrace();
}
}
//
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
// imageView.setImageBitmap(imageBitmap);
// File f = new File(currentPhotoPath);
//// Uri contentUri = Uri.fromFile(f);
// Bitmap bitmap = BitmapFactory.decodeFile(currentPhotoPath);
// //Convert bitmap to byteArray
// ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
// bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
// byte[] byteArray = byteArrayOutputStream .toByteArray();
// //Then convert to base64
// encodedImage= Base64.encodeToString(byteArray, Base64.DEFAULT);
// Log.d("#base64",encodedImage);
// setPic();
}
}
First of all, have the imageFile object from this line:
File imageFile = File.createTempFile(fileName,".jpg",storageDirectory);
...declared as a global in the Activity like this...
public class XYZActivity extends AppCompatActivity {
private File imageFile;
//onCreate(), onCapturePhoto(), etc methods
}
Then in onCapturePhoto():
imageFile = File.createTempFile(fileName,".jpg",storageDirectory);
Now in the onActivityResult(), if you ensure that no image was taken/clicked, you could try deleting the temporary file like this:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
//Your stuff...
}
else {
//No photo was taken or clicked...
//Thus, deleting the temporary file...
if (file.exists()) {
if (file.delete()) {
Log.i("Process", "Deletion DONE!");
}
}
}
}
If I interpreted any part of problem in a undesirable way, please let me know.

compressing selected image file/taken from camera

trying to let users add profile pictures, but I want to compress the image file before sending it to the server.
How can i compress the:
File imageFile = new File(resultUri.getPath());
Tried and searched but couldn't get to work
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
btnConfirm.setVisibility(View.VISIBLE);
btnConfirm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File imageFile = new File(resultUri.getPath());
progressDialog.show();
AndroidNetworking.upload("https://myweb.com/uploadImg.php")
.addMultipartFile("image", imageFile)
Would love to get some advice, Thanks in advance.
Check this
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeStream(imageStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
try {
stream.close();
stream = null;
} catch (IOException e) {
e.printStackTrace();
}

Capture Image and display as Base64 String

I'm an absolute newbie and want to build an app with Android that accesses the camera, takes a picture, cuts it and displays the result as Base64 code only.
I already did some research and built the following code, but the Base64 output doesn't work.
Thanks for your help!
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri imageUri = result.getUri();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
imageView.setImageBitmap(bitmap); //displaying bitmap works
} catch (IOException e) {
e.printStackTrace();
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Toast.makeText(this, ""+error, Toast.LENGTH_SHORT).show();
}
}
}
private String bitmapToBase64(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
textView.setText(byteArray); //doesnt work
}
}
You have your textView.setText(byteArray); after your 'return' statement. That statement will never be executed. I think you should do this:
String strReturn = Base64.encodeToString(byteArray, Base64.DEFAULT);
textView.setText(strReturn);
return strReturn;
Oh, yes, you are not calling the method to base64 encode the bitmap to string... you would do it this way:
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri imageUri = result.getUri();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
imageView.setImageBitmap(bitmap);
//HERE IS WHAT YOU NEED TO ADD
textView.setText(bitmapToBase64(bitmap));
} catch (IOException e) {
e.printStackTrace();
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Toast.makeText(this, ""+error, Toast.LENGTH_SHORT).show();
}
}
}
private String bitmapToBase64(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
//THIS CHANGED A BIT
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
return encodedImage;
}
Thanks for the tip. I'm afraid it didn't help. I guess that bitmap is not passed from the first method (?) to the second. Could that be? And what is the best way to fix that?
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri imageUri = result.getUri();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
Toast.makeText(this, ""+error, Toast.LENGTH_SHORT).show();
}
}
}
private String bitmapToBase64(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
String encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
textView.setText(encodedImage);
return Base64.encodeToString(byteArray, Base64.DEFAULT);
}

How to convert a captured Image or image selected from gallary to base64?

User can capture or select a image from gallery. I would like to upload that image to server.
This is my code for camera -
camera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//String encode = ImageBase64.encode(i);
startActivityForResult(i, CAMERA_REQUEST);
}
});
And this is my code to select a image from gallery -
gallary.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent g = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.INTERNAL_CONTENT_URI);
startActivityForResult(g, GALLARY_REQUEST);
}
});
Also, I am displaying that image with below code -
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
if(requestCode == CAMERA_REQUEST) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
uploaded_img.setImageBitmap(bitmap);
}
}
if(requestCode == GALLARY_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
uploaded_img.setImageURI(uri);
}
}
Now, I would like to convert this image to base64 and upload to server.
Here you go:
public static String convertToBase64(String path) {
Bitmap bm = BitmapFactory.decodeFile(path);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] byteArrayImage = baos.toByteArray();
String encodedImage = android.util.Base64.encodeToString(byteArrayImage, android.util.Base64.DEFAULT);
return encodedImage;
}
public static Bitmap decodeFromBase64ToBitmap(String encodedImage) {
byte[] decodedString = android.util.Base64.decode(encodedImage, android.util.Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
return decodedByte;
}
I've made it static in my project, so i don't have to create class instance.

How to add image in Sqlite database from phone gallery?

This is my code to get data from gallery and save it in SQLite database but its not working
.....
case PICK_FROM_GALLERY:
Bundle extras2 = data.getExtras();
if (extras2 != null) {
Bitmap yourImage = extras2.getParcelable("data");
// convert bitmap to byte
ByteArrayOutputStream stream = new ByteArrayOutputStream();
yourImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte imageInByte[] = stream.toByteArray();
Log.e("output before conversion", imageInByte.toString());
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
db.addContact(new Contact(resultCode, "Android", imageInByte));
Intent i = new Intent(Editor.this, Editor.class);
startActivity(i);
finish();
}
break;
}
}
Store Uri of an Image, through Uri you can set an Image in ImageView
Uri imageUri;
Intent pickUpImage = new Intent(Intent.ACTION_PICK);
pickUpImage.setType("image/*");
startActivityForResult(pickUpImage, 1);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
imageUri = uri;
profilePic.setImageURI(imageUri);
}
}

Categories