copy an image obtained by ACTION_GET_CONTENT to external storage - android

I would like to copy the image from the ACTION_GET_CONTENT and it should copy in Image directory in external storage.
I was getting the toast message but the image couldn't find in folder. Right now I giving permission manually so don't worry about that.
uriImagePath Gallary :content://com.android.providers.media.documents/document/image%3A3934
Destination: Environment.getExternalStorageDirectory().getPath() + "/Seeker/Floor Plans"
I also added permission in the manifest file.
Here is my code. Any help much appreciated.
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_CHOOSE_PICTURE_FROM_GALLARY = 22;
private static final String TAG = MainActivity.class.getSimpleName();
Button btn_copy;
private String imagepath = Environment.getExternalStorageDirectory().getPath() + "/Seeker/Floor Plans/a.png";
private Uri uriImagePath;
private String realPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_copy = findViewById(R.id.btn_copy);
}
public void CopyImage(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
imagepath = Environment.getExternalStorageDirectory().getPath() + "/Seeker/Floor Plans";
uriImagePath = Uri.fromFile(new File(imagepath));
photoPickerIntent.setType("image/*");
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriImagePath);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.name());
photoPickerIntent.putExtra("return-data", true);
startActivityForResult(photoPickerIntent, REQUEST_CODE_CHOOSE_PICTURE_FROM_GALLARY);
Toast.makeText(this, "Hi hello", Toast.LENGTH_SHORT).show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_CHOOSE_PICTURE_FROM_GALLARY && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
realPath = ImageFilePath.getPath(MainActivity.this, data.getData());
// realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());
Log.d("onActivityResult", "Destination imagePath :" + imagepath);
Log.d("onActivityResult", "uriImagePath Gallary :" + data.getData().toString());
Log.i(TAG, "onActivityResult: file path : " + realPath);
File f = new File(imagepath);
if (!f.exists())
{
try {
f.createNewFile();
copyFile(new File(getRealPathFromURI(data.getData())), f);
Log.i(TAG, "Inside if creating new file and call copy function: ");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} else {
Toast.makeText(this, "Something Went Wrong", Toast.LENGTH_SHORT).show();
}
}
private void copyFile(File sourceFile, File destFile) throws IOException {
if (!sourceFile.exists()) {
return;
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
private String getRealPathFromURI(Uri contentUri) {
String[] proj = {MediaStore.Video.Media.DATA};
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}

Related

Android app crop an image and send it to another activity

I'm creating an android app where the user crops the image, the cropped image is shown and then has to be sent in the Result activity.
The problem I have is that when I send the image, it sends me the original uncropped image.
So I wonder, am I wrong something or the image is not really cropped?
Can anyone help me figure out how to display the cropped image in the Result activity?
Thank you so much for your help guys.
onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
if (data != null) {
Uri uri = UCrop.getOutput(data);
showImage(uri);
}
} else if (requestCode == PICK_IMAGE_GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
try {
Uri sourceUri = data.getData();
File file = getImageFile();
Uri destinationUri = Uri.fromFile(file);
openCropActivity(sourceUri, destinationUri);
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),sourceUri);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
uiHelper.toast(this, "Please select another image");
}
}
}
Crop method
private void openCropActivity(Uri sourceUri, Uri destinationUri) {
UCrop.Options options = new UCrop.Options();
options.setCropFrameColor(ContextCompat.getColor(this, R.color.colorAccent));
UCrop.of(sourceUri, destinationUri)
.withMaxResultSize(1080, 540)
.withAspectRatio(16, 9)
.start(this);
}
show ImageCropped on MainActivity
private void showImage(Uri imageUri) {
try {
File file;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
file = FileUtils.getFile(this, imageUri);
} else {
file = new File(currentPhotoPath);
}
InputStream inputStream = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
uiHelper.toast(this, "Please select different profile picture.");
}
}
full code MainActivity
private static final int PICK_IMAGE_GALLERY_REQUEST_CODE = 609;
public static final int ONLY_STORAGE_REQUEST_CODE = 613;
private String currentPhotoPath = "";
private UiHelper uiHelper = new UiHelper();
private ImageView imageView;
private Button vai;
Bitmap bitmap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vai = (Button)findViewById(R.id.button);
vai.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vaiii();
}
});
findViewById(R.id.selectPictureButton).setOnClickListener(v -> {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
if (uiHelper.checkSelfPermissions(this))
uiHelper.showImagePickerDialog(this, this);
});
imageView = findViewById(R.id.imageView);
}
private void vaiii() {
Intent i = new Intent(this, risult.class);
// your bitmap
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bs);
i.putExtra("byteArray", bs.toByteArray());
startActivity(i);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == UCrop.REQUEST_CROP && resultCode == RESULT_OK) {
if (data != null) {
Uri uri = UCrop.getOutput(data);
showImage(uri);
}
} else if (requestCode == PICK_IMAGE_GALLERY_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
try {
Uri sourceUri = data.getData();
File file = getImageFile();
Uri destinationUri = Uri.fromFile(file);
openCropActivity(sourceUri, destinationUri);
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),sourceUri);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
uiHelper.toast(this, "Please select another image");
}
}
}
private void openImagesDocument() {
Intent pictureIntent = new Intent(Intent.ACTION_GET_CONTENT);
pictureIntent.setType("image/*");
pictureIntent.addCategory(Intent.CATEGORY_OPENABLE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
String[] mimeTypes = new String[]{"image/jpeg", "image/png"};
pictureIntent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
}
startActivityForResult(Intent.createChooser(pictureIntent, "Select Picture"), PICK_IMAGE_GALLERY_REQUEST_CODE);
}
private void showImage(Uri imageUri) {
try {
File file;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
file = FileUtils.getFile(this, imageUri);
} else {
file = new File(currentPhotoPath);
}
InputStream inputStream = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
uiHelper.toast(this, "Please select different profile picture.");
}
}
#Override
public void onOptionSelected(ImagePickerEnum imagePickerEnum) {
if (imagePickerEnum == ImagePickerEnum.FROM_GALLERY)
openImagesDocument();
}
private File getImageFile() throws IOException {
String imageFileName = "JPEG_" + System.currentTimeMillis() + "_";
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM
), "Camera"
);
System.out.println(storageDir.getAbsolutePath());
if (storageDir.exists())
System.out.println("File exists");
else
System.out.println("File not exists");
File file = File.createTempFile(
imageFileName, ".jpg", storageDir
);
currentPhotoPath = "file:" + file.getAbsolutePath();
return file;
}
private void openCropActivity(Uri sourceUri, Uri destinationUri) {
UCrop.Options options = new UCrop.Options();
options.setCropFrameColor(ContextCompat.getColor(this, R.color.colorAccent));
UCrop.of(sourceUri, destinationUri)
.withMaxResultSize(1080, 540)
.withAspectRatio(16, 9)
.start(this);
}
}
Activity Result
if(getIntent().hasExtra("byteArray")) {
ImageView previewThumbnail = new ImageView(this);
Bitmap b = BitmapFactory.decodeByteArray(
getIntent().getByteArrayExtra("byteArray"),0,getIntent()
.getByteArrayExtra("byteArray").length);
star.setImageBitmap(b);
previewThumbnail.setImageBitmap(b);
}

how to compress the bitmap image?

I want to upload image to the server. Converted my image as bitmap but still getting error. Bitmap too large to be uploaded into a texture
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == this.RESULT_CANCELED) {
return;
}
if (requestCode == GALLERY) {
if (data != null) {
contentURI = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentURI, filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
if (l == 0) {
imagePath = cursor.getString(columnIndex);
}
}
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), contentURI);
String path = saveImage(bitmap);
Toast.makeText(SignUpActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
BitmapDrawable bdrawable = new BitmapDrawable(this.getResources(), bitmap);
if (l == 0) {
captureAadhar.setBackground(bdrawable);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
else if (requestCode == CAMERA) {
//if (checkPermissionREAD_EXTERNAL_STORAGE(this)) {
// do your stuff..
if (data != null) {
contentURI = data.getData();
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToLast();
if (l == 0) {
imagePath = cursor.getString(column_index_data);
}
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
BitmapDrawable bdrawable = new BitmapDrawable(this.getResources(), thumbnail);
if (l == 0) {
captureAadhar.setBackground(bdrawable);
}
saveImage(thumbnail);
Toast.makeText(SignUpActivity.this, "Image Saved!", Toast.LENGTH_SHORT).show();
}
If i get picture using gallery means I am getting error as "Bitmap too large to be uploaded into a texture"
and if i get picture using camera means getting error as
"Caused by: java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaProvider uri content://media/external/images/media from pid=18253, uid=10257 requires android.permission.READ_EXTERNAL_STORAGE, or grantUriPermission()"
public String saveImage(Bitmap myBitmap) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
myBitmap.compress( Bitmap.CompressFormat.JPEG, 90, bytes );
wallpaperDirectory = new File( Environment.getExternalStorageDirectory() + IMAGE_DIRECTORY );
// have the object build the directory structure, if needed.
if (!wallpaperDirectory.exists()) {
wallpaperDirectory.mkdirs();
}
try {
f = new File( wallpaperDirectory, Calendar.getInstance().getTimeInMillis() + ".jpg" );
f.createNewFile();
FileOutputStream fo = new FileOutputStream( f );
fo.write( bytes.toByteArray() );
MediaScannerConnection.scanFile( this, new String[]{f.getPath()}, new String[]{"image/jpeg"}, null );
fo.close();
Log.d( "TAG", "File Saved::--->" + f.getAbsolutePath() );
return f.getAbsolutePath();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
Try this, link to library
https://github.com/Tourenathan-G5organisation/SiliCompressor
/**
* Request Permission for writing to External Storage in 6.0 and up
*/
private void requestPermissions(int mediaType) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
if (mediaType == TYPE_IMAGE) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_STORAGE);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_WRITE_STORAGE_VID);
}
} else {
if (mediaType == TYPE_IMAGE) {
// Want to compress an image
dispatchTakePictureIntent();
} else if (mediaType == TYPE_VIDEO) {
// Want to compress a video
dispatchTakeVideoIntent();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_STORAGE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
dispatchTakePictureIntent();
} else {
Toast.makeText(this, "You need to enable the permission for External Storage Write" +
" to test out this library.", Toast.LENGTH_LONG).show();
return;
}
break;
}
case MY_PERMISSIONS_REQUEST_WRITE_STORAGE_VID: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
dispatchTakeVideoIntent();
} else {
Toast.makeText(this, "You need to enable the permission for External Storage Write" +
" to test out this library.", Toast.LENGTH_LONG).show();
return;
}
break;
}
default:
}
}
private File createMediaFile(int type) throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fileName = (type == TYPE_IMAGE) ? "JPEG_" + timeStamp + "_" : "VID_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
type == TYPE_IMAGE ? Environment.DIRECTORY_PICTURES : Environment.DIRECTORY_MOVIES);
File file = File.createTempFile(
fileName, /* prefix */
type == TYPE_IMAGE ? ".jpg" : ".mp4", /* suffix */
storageDir /* directory */
);
// Get the path of the file created
mCurrentPhotoPath = file.getAbsolutePath();
Log.d(LOG_TAG, "mCurrentPhotoPath: " + mCurrentPhotoPath);
return file;
}
private void dispatchTakePictureIntent() {
/*Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");*/
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createMediaFile(TYPE_IMAGE);
} catch (IOException ex) {
// Error occurred while creating the File
Log.d(LOG_TAG, "Error occurred while creating the file");
}
// Continue only if the File was successfully created
if (photoFile != null) {
// Get the content URI for the image file
capturedUri = FileProvider.getUriForFile(this,
FILE_PROVIDER_AUTHORITY,
photoFile);
Log.d(LOG_TAG, "Log1: " + String.valueOf(capturedUri));
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedUri);
startActivityForResult(takePictureIntent, REQUEST_TAKE_CAMERA_PHOTO);
}
}
}
private void dispatchTakeVideoIntent() {
Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
takeVideoIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
try {
takeVideoIntent.putExtra(MediaStore.EXTRA_DURATION_LIMIT, 10);
takeVideoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
capturedUri = FileProvider.getUriForFile(this,
FILE_PROVIDER_AUTHORITY,
createMediaFile(TYPE_VIDEO));
takeVideoIntent.putExtra(MediaStore.EXTRA_OUTPUT, capturedUri);
Log.d(LOG_TAG, "VideoUri: " + capturedUri.toString());
startActivityForResult(takeVideoIntent, REQUEST_TAKE_VIDEO);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Method which will process the captured image
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//verify if the image was gotten successfully
if (requestCode == REQUEST_TAKE_CAMERA_PHOTO && resultCode == Activity.RESULT_OK) {
new ImageCompressionAsyncTask(this).execute(mCurrentPhotoPath,
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Silicompressor/images");
} else if (requestCode == REQUEST_TAKE_VIDEO && resultCode == RESULT_OK) {
if (data.getData() != null) {
//create destination directory
File f = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES) + "/Silicompressor/videos");
if (f.mkdirs() || f.isDirectory())
//compress and output new video specs
new VideoCompressAsyncTask(this).execute(mCurrentPhotoPath, f.getPath());
}
}
}
class ImageCompressionAsyncTask extends AsyncTask {
Context mContext;
public ImageCompressionAsyncTask(Context context) {
mContext = context;
}
#Override
protected String doInBackground(String... params) {
String filePath = SiliCompressor.with(mContext).compress(params[0], new File(params[1]));
return filePath;
/*
Bitmap compressBitMap = null;
try {
compressBitMap = SiliCompressor.with(mContext).getCompressBitmap(params[0], true);
return compressBitMap;
} catch (IOException e) {
e.printStackTrace();
}
return compressBitMap;
*/
}
#Override
protected void onPostExecute(String s) {
/*
if (null != s){
imageView.setImageBitmap(s);
int compressHieght = s.getHeight();
int compressWidth = s.getWidth();
float length = s.getByteCount() / 1024f; // Size in KB;
String text = String.format("Name: %s\nSize: %fKB\nWidth: %d\nHeight: %d", "ff", length, compressWidth, compressHieght);
picDescription.setVisibility(View.VISIBLE);
picDescription.setText(text);
}
*/
File imageFile = new File(s);
compressUri = Uri.fromFile(imageFile);
//FileProvider.getUriForFile(mContext, mContext.getApplicationContext().getPackageName()+ FILE_PROVIDER_EXTENTION, imageFile);
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), compressUri);
imageView.setImageBitmap(bitmap);
String name = imageFile.getName();
float length = imageFile.length() / 1024f; // Size in KB
int compressWidth = bitmap.getWidth();
int compressHieght = bitmap.getHeight();
String text = String.format(Locale.US, "Name: %s\nSize: %fKB\nWidth: %d\nHeight: %d", name, length, compressWidth, compressHieght);
picDescription.setVisibility(View.VISIBLE);
picDescription.setText(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}
As for loading large bimaps, read docs: https://developer.android.com/topic/performance/graphics/load-bitmap
Basically, you should provide inSampleSize to load load scaled version. Don't try to decode large bitmap without scaling, this will fail.

Pick image from Gallery - File not found when running newer Android versions

I am working on a address book like Android SDK 14+ app. The users should be able to pick an image from the Gallery to add it to a contact entry.
Running the following code to pick and copy the image is no problem in API 14-20 but does not work in API 21+. The file is not found anymore:
protected void pickFoto() {
if (filePermissionsRequired()) {
askForFilePermissions(new PermissionRequestCompletionHandler() {
#Override
public void onPermissionRequestResult(boolean permissionGranted) {
if (permissionGranted)
addOrEditReceipt();
}
});
return;
}
Intent pickPhotoIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhotoIntent , PICK_FOTO_ACTION);
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
...
case PICK_FOTO_ACTION: {
Uri imageUri = intent.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
File imgFile = new File(filePath);
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
public interface PermissionRequestCompletionHandler {
void onPermissionRequestResult(boolean permissionGranted);
}
private PermissionRequestCompletionHandler permissionRequestCompletionHandler;
public boolean filePermissionsRequired() {
if (Build.VERSION.SDK_INT >= 23)
return checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED;
else
return false;
}
public boolean askForFilePermissions(PermissionRequestCompletionHandler completionHandler) {
if (Build.VERSION.SDK_INT >= 23) {
permissionRequestCompletionHandler = completionHandler;
boolean hasPermission = this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
if (!hasPermission) {
this.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
return true;
}
}
permissionRequestCompletionHandler = null;
return false;
}
The app has runtime permissions to access the Gallery. So what am I doing wrong? How to access the file on newer API versions?
}
try below code to open the camera and getting result:
File file = new File(Environment.getExternalStorageDirectory() + "/DCIM/", "image" + System.currentTimeMillis() + ".png");
Uri imageUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, PICK_FOTO_ACTION);
for getting result :
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
switch (requestCode) {
case PICK_FOTO_ACTION: {
Uri imageUri = imageUri;
File imgFile = new File(imageUri.getPath());
if (imgFile.exists())
// use the file...
else
Toast.makeText(this, "Image file not found", Toast.LENGTH_LONG).show();
break;
}
}
}
for getting actual path from uri :
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor == null) return null;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String s=cursor.getString(column_index);
cursor.close();
return s;
}
remove unwanted uri part :
public String RemoveUnwantedString(String pathUri){
//pathUri = "content://com.google.android.apps.photos.contentprovider/-1/2/content://media/external/video/media/5213/ORIGINAL/NONE/2106970034"
String[] d1 = pathUri.split("content://");
for (String item1:d1) {
if (item1.contains("media/")) {
String[] d2 = item1.split("/ORIGINAL/");
for (String item2:d2) {
if (item2.contains("media/")) {
pathUri = "content://" + item2;
break;
}
}
break;
}
}
//pathUri = "content://media/external/video/media/5213"
return pathUri;
}
For versions 21 and higher you can do this , you need to add a condition to check the SDK version for this. Exectute this code in the API 21+ condition block.
String wholeID = DocumentsContract.getDocumentId(imageUri );
String id = wholeID.split(":")[1];
String sel = MediaStore.Images.Media._ID + "=?";
cursor =
getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection, sel, new String[]{ id }, null);
try
{
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
}
catch(NullPointerException e) {
}
Call the Gallery with belo code
public static final int SELECT_IMAGE_FROM_GALLERY_CODE = 701;
public static void callGallery(Activity activity) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
activity.startActivityForResult(Intent.createChooser(intent, "Complete action using"),
SELECT_IMAGE_FROM_GALLERY_CODE);
}
In OnActivityResult, read URI and read path from uri.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CommonUtils.SELECT_IMAGE_FROM_GALLERY_CODE) {
if (data != null) {
Uri selectedImageUri = data.getData();
// get path from Uri
String imagepath = getPath(this, selectedImageUri);
if (null != imagepath && (!imagepath.isEmpty())) {
// if the image path is not null and not empty, copy image to sdcard
try {
copyDirectoryOrFile(new File(imagepath), new File(myTargetImageFilePath));
} catch (IOException e) {
e.printStackTrace();
}
// load the image into imageView with the help og glide.
loadImageWithGlide(myImageViewContactImage,
myTargetImageFilePath, myDefaultImagePath, myErrorImagePath, false);
} else {
Toast.makeText(this, "Error: Photo selection failed.", Toast.LENGTH_LONG).show();
}
}
}
}
public void loadImageWithGlide(ImageView theImageViewToLoadImage,
String theLoadImagePath, int theDefaultImagePath, int theErrorImagePath,
boolean theIsSkipMemoryCache) {
if (theIsSkipMemoryCache) {
Glide.with(ProfileActivity.this) //passing context
.load(theLoadImagePath) //passing your url to load image.
.placeholder(theDefaultImagePath) //this would be your default image (like default profile or logo etc). it would be loaded at initial time and it will replace with your loaded image once glide successfully load image using url.
.error(theErrorImagePath)//in case of any glide exception or not able to download then this image will be appear . if you won't mention this error() then nothing to worry placeHolder image would be remain as it is.
.diskCacheStrategy(DiskCacheStrategy.ALL) //using to load into cache then second time it will load fast.
//.animate(R.anim.fade_in) // when image (url) will be loaded by glide then this face in animation help to replace url image in the place of placeHolder (default) image.
.centerCrop()
.into(theImageViewToLoadImage); //pass imageView reference to appear the image.
} else {
Glide.with(ProfileActivity.this)
.load(theLoadImagePath)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.centerCrop()
.into(theImageViewToLoadImage);
}
}
public static String getPath(Context theCtx, Uri uri) {
try {
Cursor cursor = (theCtx).getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = (theCtx).getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
} catch (Exception e) {
return null;
}
}
public static void copyDirectoryOrFile(File sourceLocation, File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists() && !targetLocation.mkdirs()) {
throw new IOException("Cannot create directory " + targetLocation.getAbsolutePath());
}
String[] children = sourceLocation.list();
for (int i = 0; i < children.length; i++) {
copyDirectoryOrFile(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
File directory = targetLocation.getParentFile();
if (directory != null && !directory.exists() && !directory.mkdirs()) {
throw new IOException("Cannot create directory " + directory.getAbsolutePath());
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
To load image with glide, add following dependency in app gradle file
compile 'com.github.bumptech.glide:glide:3.7.0'

How can I get the path from a file

I'm making an App where I call the file explorer, the when I choose a file i get the name with file.getName() and put it in a TextView and get the path with file..getPath() and save it in a String, this String I use it to attach the file into a mail... my problem is that when a choose a file like .PDF, .DOC, .DOCX, .MP3 I can attach it but when a select an image I get this kind of path: "/media/external/images/media/1220" and does not attach anithing, I've been serarching everywhere and use almost every option I have found with no result.
Here is my code:
private void PickFile(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, PICKER);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((resultCode == RESULT_OK) && (requestCode == PICKER)) {
String FilePath = data.getData().getPath();
File file = new File(FilePath);
}
if (txtAdjunto1.getText() == "_") {
adjunto1 = file.getPath();// I get the path to add it to the MimeBodyPart
txtAdjunto1.setText(file.getName());// I put the name in the TextView
I've been trying this:
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
int column_index;
String ruta = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor != null){
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
ruta = cursor.getString(column_index);
}
return ruta;
} finally {
if (cursor != null) {
cursor.close();
}
}
But the app crashes when I pick the file.
Also tried this:
file = new File(file.getAbsolutePath());
But still geting this "/media/external/images/media/1220"...
Hop someone can help me with this, and thanks in advance
ACTION_GET_CONTENT and ACTION_OPEN_DOCUMENT allow the user to choose a piece of content. That content might be a local file. That content might also be:
Something on a file server on the network
Something in a cloud storage service, such as Google Drive
Something in an encrypted volume
Something that is a file, but is not a file that you can access directly
And so on
You have two main options. If you only want files, then use a third-party file chooser library to replace all of the code in your question.
Or, you can take the Uri that you get from data.getData() in onActivityResult() and do two things with it:
First, use DocumentFile.fromSingleUri() to get a DocumentFile object pointing to that Uri. You can call getName() on the DocumentFile to get a "display name" for the content, which should be something that the user will recognize.
Then, use a ContentResolver and openInputStream() to get at the content itself, similar to how you might use a FileInputStream to get at the bytes in a file.
Try this...
The following code is to select any type of file from file manager and camera then convert to byte array and attach file make edit as per your requirement
private void selectFile() {
final CharSequence[] items = {"Camera", "Choose from File Manager",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(ComposeActivity.this);
builder.setTitle("Add Attachment!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Constant.checkPermission(ComposeActivity.this);
if (items[item].equals("Camera")) {
userChoosenTask = "Camera";//String
if (result)
cameraIntent();
} else if (items[item].equals("Choose from File Manager")) {
userChoosenTask = "Choose from File Manager";//String
if (result) {
FileManagerIntent();
}
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
to call camera
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
file from file manager
private void FileManagerIntent() {
try {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Select File"), 111);
} catch (Exception e) {
// Handle exceptions here
e.printStackTrace();
}
}
results
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
getting camera result and converting it to bytearray
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
Uri uri = Uri.fromFile(destination);
String uriString = uri.toString();
String path = destination.getAbsolutePath();
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = ComposeActivity.this.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
strFileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
strFileName = destination.getName();
}
attachLayout.setVisibility(View.VISIBLE);
txtFileName.setText(strFileName);
try {
fileByteArray = bytes.toByteArray();
strFile = Base64.encodeToString(fileByteArray, Base64.DEFAULT);
Log.v("Soma", strFile);
Log.v("Byte Array * ", strFile);
} catch (Exception e) {
e.printStackTrace();
}
}
result from file manager
private void onSelectFromGalleryResult(Intent data) {
Uri uri = data.getData();
if (uri.toString().contains("video") || uri.toString().contains("audio")) {
Toast.makeText(ComposeActivity.this, "Oops! can't send video/audio file", Toast.LENGTH_SHORT).show();
} else {
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = ComposeActivity.this.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
strFileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
strFileName = myFile.getName();
}
Log.v("Super DisplayName", strFileName);
attachLayout.setVisibility(View.VISIBLE);
txtFileName.setText(strFileName);
try {
InputStream iStream = getContentResolver().openInputStream(uri);
fileByteArray = getBytes(iStream);
strFile = Base64.encodeToString(fileByteArray, Base64.DEFAULT);
Log.v("Byte Array * ", strFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
file to bytearray
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}

Not able to upload image from camera in android

I am working on an app in which I want to get image from gallery or camera and then send it to server using multipart. I am able to send picture from gallery to server but when I tried to send image from camera it shows me failure.
// code for the same
// code fro open camera
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
// on activity result
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CAMERA) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
Log.d("TAG", "onActivityResult: "+Uri.fromFile(destination));
filePath = destination.toString();
if (filePath != null) {
try {
execMultipartPost();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "Image not capturd!", Toast.LENGTH_LONG).show();
}
}
// send to server code
private void execMultipartPost() throws Exception {
File file = new File(filePath);
String contentType = file.toURL().openConnection().getContentType();
Log.d("TAG", "file new path: " + file.getPath());
Log.d("TAG", "contentType: " + contentType);
RequestBody fileBody = RequestBody.create(MediaType.parse(contentType), file);
final String filename = "file_" + System.currentTimeMillis() / 1000L;
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("date", "21-09-2017")
.addFormDataPart("time", "11.56")
.addFormDataPart("description", "hello")
.addFormDataPart("image", filename + ".jpg", fileBody)
.build();
Log.d("TAG", "execMultipartPost: "+requestBody);
okhttp3.Request request = new okhttp3.Request.Builder()
.url("http://myexample/api/user/lets_send")
.post(requestBody)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, final IOException e) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(), "nah", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResponse(Call call, final okhttp3.Response response) throws IOException {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Log.d("TAG", "response of image: " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
});
}
Try This, it may help
Intent takePhotoIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Date date = new Date();
String timeStamp = new SimpleDateFormat(pictureNameDateFormat, Locale.US).format(date.getTime());
File fileDirectory = new File(Environment.getExternalStorageDirectory() + "/Pictures");
if (fileDirectory.exists()) {
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(
new File(Environment.getExternalStorageDirectory() + "/Pictures/picture_"+ timeStamp + ".png")));
takePhotoIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
takePhotoIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
if (takePhotoIntent.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivityForResult(takeVideoIntent, captureVideoActivityRequestCode);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("path",Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg");
}
Please use below code to capture image by camera and for pick image from gallery and you can crop also.
First of all please add this dependency in your build.gradle
compile 'com.theartofdev.edmodo:android-image-cropper:2.3.+'
In your Activity please add this code :
uploadPic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onSelectImageClick(view);
}
});
/**
* Start pick image activity with chooser.
*/
public void onSelectImageClick(View view) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(AccountSettingActivity.this, new String[]{android.Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE}, MY_REQUEST_CAMERA);
} else if (ContextCompat.checkSelfPermission(AccountSettingActivity.this, android.Manifest.permission.CAMERA) + ContextCompat.checkSelfPermission(AccountSettingActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
CropImage.startPickImageActivity(this);
}
}else {
CropImage.startPickImageActivity(this);
}
}
#Override
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// handle result of pick image chooser
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri imageUri = CropImage.getPickImageResultUri(this, data);
startCropImageActivity(imageUri);
}
// handle result of CropImageActivity
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
fileUri = result.getUri();
userImage.setImageURI(result.getUri());
Toast.makeText(this, "Cropping successful, Sample: " + result.getSampleSize(), Toast.LENGTH_LONG).show();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Toast.makeText(this, "Cropping failed: " + result.getError(), Toast.LENGTH_LONG).show();
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED ) {
CropImage.startPickImageActivity(this);
} else {
Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
/**
* Start crop image activity for the given image.
*/
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setMultiTouchEnabled(true)
.start(this);
}
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
in manifest please add these permissions and ask for run time permissions also ,this may solve your problem ,Your coding is correct those works for me perfectly after adding permission.
Please go trough the following code
try {
if (imageUri != null) {
photo = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(imageUri));
} else {
photo = (Bitmap) data.getExtras().get("data");
}
Uri tempUri = CommonData.getImageUri(getContext(), photo);
uri = tempUri.toString();
String path = CommonData.convertImageUriToFile(tempUri, getActivity());
// new PreprocessImagesTask().execute(path);
showLoader();
new ProcessingImage(this).execute(path);
} catch (Exception e) {
e.printStackTrace();
}
public static Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public static String convertImageUriToFile(Uri imageUri, Activity activity) {
String imgPath = "";
String Path;
try {
Cursor cursor = null;
int imageID = 0;
try {
/* ********** Which columns values want to get ****** */
String[] proj = {
MediaStore.Images.Media.DATA,
MediaStore.Images.Media._ID,
MediaStore.Images.Thumbnails._ID,
MediaStore.Images.ImageColumns.ORIENTATION
};
cursor = activity.getContentResolver().query(
imageUri, // Get data for specific image URI
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null // Order-by clause (ascending by name)
);
int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
int size = cursor.getCount();
/* ****** If size is 0, there are no images on the SD Card. **** */
if (size == 0) {
// imageDetails.setText("No Image");
} else {
int thumbID = 0;
if (cursor.moveToFirst()) {
Path = cursor.getString(file_ColumnIndex);
//String orientation = cursor.getString(orientation_ColumnIndex);
String CapturedImageDetails = " CapturedImageDetails : \n\n"
+ " ImageID :" + imageID + "\n"
+ " ThumbID :" + thumbID + "\n"
+ " Path :" + Path + "\n";
showLog("CapturedImageDetails", CapturedImageDetails);
imgPath = Path;
// Show Captured Image detail on view
// imageDetails.setText(CapturedImageDetails);
}
}
} finally {
if (cursor != null) {
cursor.close();
}
}
return "" + imgPath;
} catch (IllegalArgumentException e) {
e.printStackTrace();
return "";
}
}
Give a try!
private static final int REQUEST_IMAGE = 100;
private static final String TAG = "MainActivity";
TextView imgPath;
ImageView picture;
File destination;
String imagePath;
//onCreate
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
startActivityForResult(intent, REQUEST_IMAGE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK ){
try {
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
imagePath = destination.getAbsolutePath();//get your path
imgPath.setText(imagePath);
Bitmap bmp = BitmapFactory.decodeStream(in, null, options);
picture.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else{
imgPath.setText("Request cancelled");
}
}

Categories

Resources