Declare and
initilize before OnCreate
private static int RESULT_LOAD_IMG = 1;
String imgDecodableStringPath; // file path
Inside Oncreate -
Button clickevent
// Create intent to Open Image applications like
Gallery,Google//Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
OutSide Oncreate
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&&
null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableStringPath = cursor.getString(columnIndex);
cursor.close();
Log.v("Path of
Image file ->", imgDecodableStringPath);
/*
* Step 1 -
Converting File into BitMap Step 2 - Converting
* Bitmap into
ByteArray Step 3- Converting Byte Array into
*
Base64DataString
*/
Utility.getBytes((BitmapFactory.decodeFile(imgDecodableStringPath)));
String Base64DataSring = Base64.encodeToString(Utility.getBytes((BitmapFactory
.decodeFile(imgDecodableStringPath))),Base64.DEFAULT);
Log.v("Base64DataSring
String ->", Base64DataSring);
} else {
Toast.makeText(this, "You haven't
picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something
went wrong", Toast.LENGTH_LONG)
.show();
}
}
=============================================
Utility.java
public class Utility {
// convert
from bitmap to byte array
public static byte[]
getBytes(Bitmap bitmap) {
ByteArrayOutputStream
stream = new
ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
// convert
from byte array to bitmap
public static Bitmap
getPhoto(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}
No comments:
Post a Comment