This question already has answers here:
Camera Intent Not Adding Extra
(1 answer)
Failure delivering result ResultInfo{who=null, request=2, result=-1, data=Intent { }} to activity
(1 answer)
Closed 5 years ago.
I want to get the pic taken by the camera, but the intent in onActivityResult is always null, I've tried several ways, but they didn't work. Here is the code i use camera:
private static final int REQUEST_FROM_CAMERA = 37;
public void takePhotoByCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = new File(Environment.getExternalStorageDirectory(),
"nameOfFile" + String.valueOf(System.currentTimeMillis()) + ".jpg");
Const.uri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Const.uri);
intent.putExtra("return data", true);
((UploadLicenseActivity) mContext).startActivityForResult(intent, REQUEST_FROM_CAMERA);
}
I provided MediaStore.EXTRA_OUTPUT and test the uri is not null.
And onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (data == null)
Log.e("data", "data is null");
else if (data.getData() == null)
Log.e("data.getData", "data.getData is null");
if (requestCode == REQUEST_FROM_CAMERA && null != data && null != data.getData()) {
if (null != Const.uri) {
uploadLicensePresenter.startCropActivity(Const.uri);
} else {
Toast.makeText(this, "Cannot retrieve selected image.", Toast.LENGTH_SHORT).show();
}
}
}
}
The logcat:
03-21 13:45:49.705 16424-16424/com.ssl.pdpatrol E/data: data is null
Why data is null, and how can I solve it?
Try this:
private int REQUEST_TAKE_PHOTO = 1;
private Uri camera_FileUri;
Bitmap bitMapThumbnail;
//image click listener
if (Build.VERSION.SDK_INT >= 23) {
// Marshmallow+
if (!checkAccessFineLocationPermission() || !checkAccessCoarseLocationPermission() || !checkWriteExternalStoragePermission()) {
requestPermission();
} else {
chooseimage();
}
} else {
chooseimage();
}
private void chooseimage() {\
takePicture();
}
private void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
camera_FileUri = getOutputMediaFileUri(1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, camera_FileUri);
// start the image capture Intent
startActivityForResult(intent, REQUEST_TAKE_PHOTO);
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), IMAGE_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == 1) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", camera_FileUri);
}
//require premission
private boolean checkAccessFineLocationPermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private boolean checkAccessCoarseLocationPermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private boolean checkWriteExternalStoragePermission() {
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
chooseimage();
} else {
finish();
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_PHOTO) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap bitmap = BitmapFactory.decodeFile(camera_FileUri.getPath(), options);
Bitmap thumbnail = bitmap;
final String picturePath = camera_FileUri.getPath();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
File curFile = new File(picturePath);
try {
ExifInterface exif = new ExifInterface(curFile.getPath());
int rotation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
int rotationInDegrees = exifToDegrees(rotation);
Matrix matrix = new Matrix();
if (rotation != 0f) {
matrix.preRotate(rotationInDegrees);
}
thumbnail = Bitmap.createBitmap(thumbnail, 0, 0, thumbnail.getWidth(), thumbnail.getHeight(), matrix, true);
} catch (IOException ex) {
Log.e("TAG", "Failed to get Exif data", ex);
}
thumbnail.compress(Bitmap.CompressFormat.JPEG, 70, byteArrayOutputStream);
//------------Code to update----------
bitMapThumbnail = thumbnail;
profile_pic.setImageBitmap(thumbnail);
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can Try this
if (requestCode == REQUEST_FROM_CAMERA && resultCode == RESULT_OK)
{
Bundle extras2 = data.getExtras();
if (extras2 != null) {
// do your stuff here
}
else {
// handle this case as well if data.getExtras() is null
Uri selectedImage = data.getData();
}
}
Hope it helps you
Related
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);
}
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.
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");
}
}
Hi I am using camera and gallery button. When I select camera, I display by opening camera, taking picture and sending that picture to next activity through intent. This works fine.
But when I select gallery button, it opens gallery image but it's not displaying image in next activity. There is no error. Just a blank black screen.
It displays as,
I/Choreographer: Skipped 2103 frames! The application may be doing too much work on its main thread.
Please help to solve this.
Thanks.
public class TestCameraActivity extends AppCompatActivity {
private CameraPreview mImageSurfaceView;
public Camera camera = null;
public static final int MEDIA_TYPE_IMAGE = 1;
private static final int REQUEST_CAMERA_PERMISSION = 1;
private static final int REQUEST_WRITE_PERMISSION = 2;
private FrameLayout cameraPreviewLayout;
private float mDist;
private Bitmap bm;
private float ratio = 9f / 16f;
private Button gallery;
private int SELECT_FILE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test_camera);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
cameraPreviewLayout = (FrameLayout) findViewById(R.id.camera_preview);
Button captureButton = (Button) findViewById(R.id.button);
gallery = (Button) findViewById(R.id.galleries);
gallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),SELECT_FILE);
}
});
captureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
camera.takePicture(null, null, pictureCallback);
}
});
}
#Override
protected void onResume() {
super.onResume();
requestCameraPermission();
}
Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
bm = BitmapFactory.decodeByteArray(data, 0, data.length);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
// Setting post rotate to 90
Matrix mtx = new Matrix();
mtx.postRotate(90);
bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), mtx, true);
bm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), (int) (bm.getWidth() * ratio));
} else {// LANDSCAPE MODE
//No need to reverse width and height
Bitmap scaled = Bitmap.createScaledBitmap(bm, bm.getWidth(), bm.getHeight(), true);
bm = scaled;
}
if (bm == null) {
Toast.makeText(TestCameraActivity.this, "khoong duoc roi", Toast.LENGTH_LONG).show();
return;
}
// capturedImageHolder.setImageBitmap(bm);
Intent intent = new Intent(TestCameraActivity.this, CaptureResultActivity.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 60, bs);
intent.putExtra("bitmap", bs.toByteArray());
startActivity(intent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestWritePermission();
} else {
asyncSave();
}
// camera.startPreview();
}
};
public void asyncSave() {
new AsyncTask<Bitmap, Void, Boolean>() {
#Override
protected Boolean doInBackground(Bitmap... bitmaps) {
return saveBitmapImage(bitmaps[0]);
}
#Override
protected void onPostExecute(Boolean aBoolean) {
if (aBoolean) {
Toast.makeText(TestCameraActivity.this, "Save Image Success", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(TestCameraActivity.this, "Failed to save image...", Toast.LENGTH_SHORT).show();
}
}
}.execute(bm);
}
private boolean saveBitmapImage(Bitmap bitmap) {
File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
if (pictureFile == null) {
Log.d("BBB", "Error creating media file, check storage permissions: ");
return false;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
// fos.write(data);
fos.close();
galleryAddPic(pictureFile);
return true;
} catch (FileNotFoundException e) {
Log.d("BBB", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("BBB", "Error accessing file: " + e.getMessage());
}
return false;
}
private static File getOutputMediaFile(int type) {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyCameraApp");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_LINH" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
// zoom
#Override
public boolean onTouchEvent(MotionEvent event) {
// Get the pointer ID
Camera.Parameters params = camera.getParameters();
int action = event.getAction();
if (event.getPointerCount() > 1) {
// handle multi-touch events
if (action == MotionEvent.ACTION_POINTER_DOWN) {
mDist = getFingerSpacing(event);
} else if (action == MotionEvent.ACTION_MOVE && params.isZoomSupported()) {
camera.cancelAutoFocus();
handleZoom(event, params);
}
} else {
// handle single touch events
if (action == MotionEvent.ACTION_UP) {
handleFocus(event, params);
}
}
return true;
}
private void handleZoom(MotionEvent event, Camera.Parameters params) {
int maxZoom = params.getMaxZoom();
int zoom = params.getZoom();
float newDist = getFingerSpacing(event);
if (newDist > mDist) {
//zoom in
if (zoom < maxZoom)
zoom++;
} else if (newDist < mDist) {
//zoom out
if (zoom > 0)
zoom--;
}
mDist = newDist;
params.setZoom(zoom);
camera.setParameters(params);
}
public void handleFocus(MotionEvent event, Camera.Parameters params) {
int pointerId = event.getPointerId(0);
int pointerIndex = event.findPointerIndex(pointerId);
// Get the pointer's current position
float x = event.getX(pointerIndex);
float y = event.getY(pointerIndex);
List<String> supportedFocusModes = params.getSupportedFocusModes();
if (supportedFocusModes != null && supportedFocusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
camera.autoFocus(new Camera.AutoFocusCallback() {
#Override
public void onAutoFocus(boolean b, Camera camera) {
// currently set to auto-focus on single touch
}
});
}
}
/**
* Determine the space between the first two fingers
*/
private float getFingerSpacing(MotionEvent event) {
// ...
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return (float) Math.sqrt(x * x + y * y);
}
//Request Permission
private void requestCameraPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA_PERMISSION);
}
} else {
camera = Camera.open();
mImageSurfaceView = new CameraPreview(this, camera);
cameraPreviewLayout.addView(mImageSurfaceView);
}
} else {
camera = Camera.open();
mImageSurfaceView = new CameraPreview(this, camera);
cameraPreviewLayout.addView(mImageSurfaceView);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CAMERA_PERMISSION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
camera = Camera.open(0);
mImageSurfaceView = new CameraPreview(this, camera);
cameraPreviewLayout.addView(mImageSurfaceView);
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
case REQUEST_WRITE_PERMISSION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
asyncSave();
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
//Request Write Permission
private void requestWritePermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_WRITE_PERMISSION);
// }
} else {
asyncSave();
}
} else {
//api < 21
}
}
//Add photo to the gallery
private void galleryAddPic(File f) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
}
} catch (Exception e) {
Toast.makeText(this, "Please try again", Toast.LENGTH_LONG)
.show();
}
}
private static Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte= Base64.decode(encodedString,Base64.DEFAULT);
Bitmap bitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
Intent intent = new Intent(TestCameraActivity.this, CaptureResultActivity.class);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 60, bs);
intent.putExtra("bitmap", bs.toByteArray());
startActivity(intent);
}
}
}
First For open Gallery you need to open as per the API level. After API 19 you need to open gallery in other way.
if (Build.VERSION.SDK_INT < 19) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
} else {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("image/*");
startActivityForResult(intent, PICK_IMAGE_REQUEST);
}
And on the ActivityResult()
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_IMAGE_REQUEST
&& resultCode == Activity.RESULT_OK) {
Uri uri = data.getData();
mImageCaptureUri = Uri.fromFile(new File(uriToFilename(uri)));
}
}
private String uriToFilename(Uri uri) {
String path = null;
if (Build.VERSION.SDK_INT < 11) {
path = RealPathUtil.getRealPathFromURI_BelowAPI11(getActivity(), uri);
} else if (Build.VERSION.SDK_INT < 19) {
path = RealPathUtil.getRealPathFromURI_API11to18(getActivity(), uri);
} else {
path = RealPathUtil.getRealPathFromURI_API19(getActivity(), uri);
}
return path;
}
Here is RealPathUtil class
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
public class RealPathUtil {
#SuppressLint("NewApi")
public static String getRealPathFromURI_API19(Context context, Uri uri) {
String filePath = "";
if (DocumentsContract.isDocumentUri(context, uri)) {
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String[] splits = wholeID.split(":");
if (splits.length == 2) {
String id = splits[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[] { id }, null);
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
} else {
filePath = uri.getPath();
}
return filePath;
}
#SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
String result = null;
CursorLoader cursorLoader = new CursorLoader(context, contentUri, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
result = cursor.getString(column_index);
}
return result;
}
public static String getRealPathFromURI_BelowAPI11(Context context, Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
This code worked on samsung before but now that i'm using Nexus One with Android 2.3.6, it's crashing as soon as I take a picture and click ok or choose a photo from gallery. Stacktrace shows a null pointer exception on the Uri.
My code for the activating the camera is as follows:
public void activateCamera(View view){
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// start the image capture Intent
startActivityForResult(i, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == CHOOSE_IMAGE_ACTIVITY_REQUEST_CODE || requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE)
&& resultCode == RESULT_OK && null != data) {
selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bits = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = inSampleSize;
try {
bits = BitmapFactory.decodeStream(new FileInputStream(picturePath),null,options);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Any idea what could be the problem?
Thanks!
You have to tell the camera, where to save the picture and remeber the uri yourself:
private Uri mMakePhotoUri;
private File createImageFile() {
// return a File object for your image.
}
private void makePhoto() {
try {
File f = createImageFile();
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
mMakePhotoUri = Uri.fromFile(f);
i.putExtra(MediaStore.EXTRA_OUTPUT, mMakePhotoUri);
startActivityForResult(i, REQUEST_MAKE_PHOTO);
} catch (IOException e) {
Log.e(TAG, "IO error", e);
Toast.makeText(getActivity(), R.string.error_writing_image, Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
switch (requestCode) {
case REQUEST_MAKE_PHOTO:
if (resultCode == Activity.RESULT_OK) {
// do something with mMakePhotoUri
}
return;
default: // do nothing
super.onActivityResult(requestCode, resultCode, data);
}
}
You should save the value of mMakePhotoUri over instance states withing onCreate() and onSaveInstanceState().
Inject this extra into the Intent that called onActivityResult and the system will do all the heavy lifting for you.
File f = createImageFile();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
Doing this makes it as easy as this to retrieve the photo as a bitmap.
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(mImageBitmap);
}
dont pass any extras, just define the path where you have placed or saved the file directly in onActivityResult
public void openCamera() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = createImageFile();
boolean isDirectoryCreated = file.getParentFile().mkdirs();
Log.d("", "openCamera: isDirectoryCreated: " + isDirectoryCreated);
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
try
{
cameraIntent.putExtra("return-data", true);
startActivityForResult(cameraIntent, ScanConstants.START_CAMERA_REQUEST_CODE);
}
catch (Exception e)
{
}
}
private File createImageFile() {
clearTempImages();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new
Date());
File file = new File(ScanConstants.IMAGE_PATH, "IMG_" + timeStamp +
".jpg");
fileUri = Uri.fromFile(file);
return file;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = null ;
if (resultCode == Activity.RESULT_OK ) {
try {
if (Build.VERSION.SDK_INT >= 23) {
tempFileUri = FileProvider.getUriForFile(getActivity().getApplicationContext(),
"com.scanlibrary.provider", // As defined in Manifest
file);
} else {
tempFileUri = Uri.fromFile(file);
}
bitmap = getBitmap(tempFileUri);
bitmap = getBitmap(data.getData());
} catch (Exception e) {
e.printStackTrace();
}
} else {
getActivity().finish();
}
if (bitmap != null) {
postImagePick(bitmap);
}
}