how to canceled camera in Android Application - android

How to cancel camera when user will click on left side icon on camera in Android emulator.When i open the camera and capture the image bitmap is send to Image_Cropping for crop the image.When cancel the camera it does not comeback to previous Activity , it goes to Image_Cropping Activity.Can someone help me to resolve it.
Here is my onActivityResult code
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST)
{
if (requestCode == 0 && resultCode == 0){
Toast.makeText(getApplicationContext(),"Cancel Image Capture ", Toast.LENGTH_SHORT).show();
}else {
onCaptureImageResult(data);
}
}
if (requestCode == PROFILE_GALLERY && resultCode == RESULT_OK)
{
Uri 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 imgDecodableString = cursor.getString(columnIndex);
cursor.close();
editor.putString("profile_picformat", imgDecodableString);
editor.commit();
Intent selfiSrc = new Intent(this, Image_Cropping.class);
finish();
startActivity(selfiSrc);
}
}
btnCamera.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String picformat = "IMG_" + 0 + "_" + s.format(new Date()) + ".png";
Log.e(" picformat ", " = " + picformat);
Intent i = new Intent(Filter_Screen.this , Image_Cropping.class );
startActivity(i);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String extr = Environment.getExternalStorageDirectory().toString() + File.separator + "classNKK_ProfilePic";
File myPath = new File(extr, picformat);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(myPath));
startActivityForResult(cameraIntent, CAMERA_REQUEST);
Log.e("Camera", " Open");
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String imageUserProfile_path = baseDir + "/classNKK_ProfilePic/" + picformat;
editor.putString("profile_picformat", imageUserProfile_path);
editor.commit();
}
});
This is my ImageCropping Class
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.img_cropping);
mCropImageView = (CropImageView) findViewById(R.id.CropImageView);
dbhelper = new MyDbHelper(this);
dbhelper.onOpen(db);
Log.e(" In", " onCreate Method !!!!!!!!!!");
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
str_Authentication_Token = sharedPreferences.getString("strAuthentication_Token", "");
str_UserId = sharedPreferences.getString("strUserId", "");
str_UserName = sharedPreferences.getString("strUserName", "");
str_UserRole = sharedPreferences.getString("strUserRole", "");
str_LoginUserName = sharedPreferences.getString("strLogin_UserName" , "" );
Log.e(" ", " str_Authentication_Token= " + str_Authentication_Token + " str_UserId= " + str_UserId + " str_UserName= " + str_UserName + "str_UserRole= " + str_UserRole + " str_LoginUserName= " + str_LoginUserName);
getProfile_PicFormat = sharedPreferences.getString("profile_picformat", "");
Log.e("getImagePath ", " getPicFormat = " + getProfile_PicFormat);
Bitmap bmp = BitmapFactory.decodeFile(getProfile_PicFormat);
if (savedInstanceState == null) {
mCropImageView.setImageBitmap(bmp);
}
mCropImageView.setAspectRatio(DEFAULT_ASPECT_RATIO_VALUES, DEFAULT_ASPECT_RATIO_VALUES);
btnCropImage = (Button)findViewById(R.id.button_CropImage);
btnCropImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCropImageView.getCroppedImageAsync(mCropImageView.getCropShape(), 0, 0);
}
});
buttonDone = (Button)findViewById(R.id.button_Done);
buttonDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Intent i = new Intent(Image_Cropping.this , Filter_Screen.class);
finish();
startActivity(i);
}
});
}
// Saves the state upon rotating the screen/restarting the activity
#Override
protected void onSaveInstanceState(#SuppressWarnings("NullableProblems") Bundle bundle) {
super.onSaveInstanceState(bundle);
bundle.putInt(ASPECT_RATIO_X, mAspectRatioX);
bundle.putInt(ASPECT_RATIO_Y, mAspectRatioY);
}
// Restores the state upon rotating the screen/restarting the activity
#Override
protected void onRestoreInstanceState(#SuppressWarnings("NullableProblems") Bundle bundle) {
super.onRestoreInstanceState(bundle);
mAspectRatioX = bundle.getInt(ASPECT_RATIO_X);
mAspectRatioY = bundle.getInt(ASPECT_RATIO_Y);
}
#Override
protected void onStart() {
super.onStart();
mCropImageView.setOnSetImageUriCompleteListener(this);
mCropImageView.setOnGetCroppedImageCompleteListener(this);
}
#Override
protected void onStop() {
super.onStop();
mCropImageView.setOnSetImageUriCompleteListener(null);
mCropImageView.setOnGetCroppedImageCompleteListener(null);
}
#Override
public void onSetImageUriComplete(CropImageView view, Uri uri, Exception error) {
if (error == null) {
Toast.makeText(mCropImageView.getContext(), "Image load successful", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mCropImageView.getContext(), "Image load failed: " + error.getMessage(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onGetCroppedImageComplete(CropImageView view, Bitmap bitmap, Exception error) {
if (error == null)
{
croppedImage = bitmap;
int bitMapWidth = croppedImage.getWidth();
int bitmapHeight = croppedImage.getHeight();
Log.e("croppedImage","="+croppedImage + " bitMapWidth="+bitMapWidth + " bitmapHeight="+bitmapHeight);
String[] finalPath = getProfile_PicFormat.split("/");
final String split_CroppedString = finalPath[finalPath.length - 1];
Log.e(" split_CroppedString ", " = " + split_CroppedString);
String extr = Environment.getExternalStorageDirectory().toString() + File.separator + "classNKK_ProfilePic";
cropped_ImagePath = "Cropped_"+split_CroppedString;
Log.e("cropped_ImagePath "," ======>>" + cropped_ImagePath );
File myPath = new File(extr, cropped_ImagePath);
FileOutputStream fileOutputStream = null;
try
{
fileOutputStream = new FileOutputStream(myPath);
croppedImage.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
editor = sharedPreferences.edit();
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String cropped_UserProfilepath = baseDir + "/classNKK_ProfilePic/" + cropped_ImagePath;
editor.putString("croppedImagePath", cropped_UserProfilepath);
editor.commit();
String str_ProfilePic_UpLoadStatus = "0";
db = dbhelper.getWritableDatabase();
db.execSQL("update Inspector set ProfilePICURL = '" + cropped_ImagePath + "' , ProfilePic_UpLoadStatus='"+0+"', DownLoadStatus='1' where Inspector_Id = '" + str_UserId + "'");
db.execSQL("update ALL_Post set ProfilePICURL = '" + cropped_ImagePath + "' , DownLoad_Status='1' where UserId = '" + str_UserId + "'");
Log.e("Updated ", " Succesfully !!! ImageName = " + cropped_ImagePath);
sendPostRequest(cropped_ImagePath);
Log.e("Cropped ", " Profile Pic UpLoaded SuccesFully !!!!!!!!!!!!!! ");
String delete_cropped_UserProfilepath = baseDir + "/classNKK_ProfilePic/" + split_CroppedString;
File file= new File(delete_cropped_UserProfilepath);
if(file.exists())
{
file.delete();
Log.e("Original "," File is deleted !!!");
}
Intent i = new Intent(Image_Cropping.this , Filter_Screen.class);
startActivity(i);
finish();
} else {
Toast.makeText(mCropImageView.getContext(), "Image Crop failed: " + error.getMessage(), Toast.LENGTH_LONG).show();
}
}
private Uri getCaptureImageOutputUri() {
Uri outputFileUri = null;
File getImage = getExternalCacheDir();
if (getImage != null) {
outputFileUri = Uri.fromFile(new File(getImage.getPath(), "pickImageResult.jpeg"));
}
return outputFileUri;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Uri imageUri = getPickImageResultUri(data);
((CropImageView) findViewById(R.id.CropImageView)).setImageUriAsync(imageUri);
}
}
public Uri getPickImageResultUri(Intent data) {
boolean isCamera = true;
if (data != null) {
String action = data.getAction();
isCamera = action != null && action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
return isCamera ? getCaptureImageOutputUri() : data.getData();
}}
Thanks in advanced .

Now just copy this.
No any changes in Imagecropping clsaa.
btnCamera.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String picformat = "IMG_" + 0 + "_" + s.format(new Date()) + ".png";
Log.e(" picformat ", " = " + picformat);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String extr = Environment.getExternalStorageDirectory().toString() + File.separator + "classNKK_ProfilePic";
File myPath = new File(extr, picformat);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(myPath));
startActivityForResult(cameraIntent, CAMERA_REQUEST);
Log.e("Camera", " Open");
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String imageUserProfile_path = baseDir + "/classNKK_ProfilePic/" + picformat;
editor.putString("profile_picformat", imageUserProfile_path);
editor.commit();
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST)
{
if (requestCode == 0 && resultCode == 0){
Toast.makeText(getApplicationContext(),"Canceling Image Capture ", Toast.LENGTH_SHORT).show();
}else {
onCaptureImageResult(data);
}
}
if (requestCode == PROFILE_GALLERY && resultCode == RESULT_OK)
{
Uri 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 imgDecodableString = cursor.getString(columnIndex);
cursor.close();
editor.putString("profile_picformat", imgDecodableString);
editor.commit();
Intent selfiSrc = new Intent(this, Image_Cropping.class);
finish();
startActivity(selfiSrc);
}
}
private void onCaptureImageResult(Intent data) {
Intent selfiSrc = new Intent(this, Image_Cropping.class);
startActivity(selfiSrc);
finish();
}

Related

copy an image obtained by ACTION_GET_CONTENT to external storage

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);
}
}

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");
}
}

Picture does not show in imageview

I am opening camera on button click and taking picture and showing it in imageview. It's working in Google Nexus. But it's not working in Samsung Tab and Micromax canvas HD,Why?
My Button click code :
CAMERA_PIC_REQUEST = 100;
String path = Environment.getExternalStorageDirectory()
+ "/MySampleApp/image.jpg";
File file = new File(path);
Uri outputFileUri = Uri.fromFile(file);
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
OnActivityResult code :
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
Bitmap bitmap = BitmapFactory.decodeFile(path,
options);
mImageView.setImageBitmap(bitmap);
Permissions in manifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
Why is this code not working in samsung and micromax?
This is the correct code are not?
Any one please help me?
Try this
btn.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0)
{
CAMERA_PIC_REQUEST = 100;
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
And
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
mImageView.setImageBitmap(photo);
}
}
Try this code it will work in micromax devices..use this uri
btnGallery.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
pop.dismiss();
startActivityForResult(Intent.createChooser(intent, "Select Picture"), StaticMembers.galleryRequestCode);
}
});
ImageView btnCamera = (ImageView) pop.findViewById(R.id.ivCamera);
btnCamera.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//With Camera Utils
pop.dismiss();
outpuUri = CameraUtil.startCam(yourActivity.this);
}
});
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.d("Alpha", "onActivity : " + requestCode);
System.gc();
Log.d("Alpha", "onActivity : " + requestCode + " RESULT CODE : " + resultCode);
System.gc();
long timestamp = System.currentTimeMillis() / 1000L;
String time = timestamp + "";
String imgPath = null;
if (requestCode == CameraUtil.IMAGE_CAPTURED && resultCode == Activity.RESULT_OK)
{
if (outpuUri != null)
{
Log.d("Alpha", "URI NOT NULL");
imgPath = outpuUri.getPath();
//Log.d("Alpha", "ACT RES PATH : " + imgPath);
//mCapturedBitmap = CameraUtil.sampleBitmap(imgPath, ivHeightWidth);
//iv.setImageBitmap(mCapturedBitmap);
}
else
{
Log.d("Alpha", "URI NULL IN CAM");
}
}
else if (requestCode == StaticMembers.galleryRequestCode && resultCode == Activity.RESULT_OK)
{
outpuUri = data.getData();
imgPath = getPath(outpuUri);
mCapturedBitmap = CameraUtil.sampleBitmap(imgPath, ivHeightWidth);// BitmapFactory.decodeFile(imgPath);
iv.setImageBitmap(mCapturedBitmap);
Log.d("Alpha", "In Gallery " + imgPath);
}
if (imgPath != null)
{
showConfrirmDialog(imgPath, time);
}
}
public class CameraUtil
{
private static Uri outpuUri;
public static final int IMAGE_CAPTURED = 200;
public static String imageName;
private static String imageFolder;
public static Uri startCam(Activity context)
{
imageName = "sample" + System.currentTimeMillis() + ".jpg";
outpuUri = Uri.fromFile(new File(getImageFolderFile().getAbsolutePath() + File.separator + imageName));
Log.d("CHECK", "BEFORE STARTING CAM URI : " + outpuUri.getPath());
Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, outpuUri);
i.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
context.startActivityForResult(i, IMAGE_CAPTURED);
return outpuUri;
}
public static File getImageFolderFile()
{
imageFolder = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "sparkchat_camera_pics";
File f = new File(imageFolder);
Log.d("Alpha", f.getAbsolutePath() + " exists > " + f.exists());
if (!f.exists())
f.mkdirs();
return f;
}
}

Android ACTION_IMAGE_CAPTURE intent returns null on onActivityResult

We are facing an issue for passing intent data to onActivityResult method when we start ACTION_IMAGE_CAPTURE intent getting null for intent
Here is my code for starting camera activity and passing data to the onActivityResult()
don't know whats went wrong strange please help me out
Thanks in adavnce
public void takePicture()
{
File directory = new File(Environment.getExternalStorageDirectory() + "/AML_AttachmentImages" + "/");
if (!directory.exists())
{
directory.mkdir();
}
int count = 0;
if (directory != null)
{
File[] files = directory.listFiles();
if (files != null)
{
count = files.length;
}
}
count++;
String imagePath = "AML_IMAGE_" + count + ".jpg";
File file = new File(directory, imagePath);
outputFileUri = Uri.fromFile(file);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PHOTO_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
switch (requestCode)
{
case TAKE_PHOTO_CODE :
outputFileUri=data.getParcelableExtra(MediaStore.EXTRA_OUTPUT);
File imageFilePath = new File(outputFileUri.getPath());
imagePathUris.add(imageFilePath.getAbsolutePath());
Bitmap myBitmap = BitmapFactory.decodeFile(imageFilePath.getAbsolutePath());
bitmaps.add(myBitmap);
txtAttachmentsCount.setVisibility(View.VISIBLE);
txtAttachmentsCount.setText(getResources().getString(R.string.view_attachment_text) + Integer
.toString(imagePathUris.size()) + ")");
break;
case REQ_PIC :
final ContentResolver cr = getContentResolver();
final String[] p1 = new String[]{MediaStore.Images.ImageColumns._ID,
MediaStore.Images.ImageColumns.DATE_TAKEN};
Cursor c1 = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, p1, null, null, p1[1] + " DESC");
if (c1.moveToFirst())
{
String uristringpic = "content://media/external/images/media/" + c1.getInt(0);
Uri newuri = Uri.parse(uristringpic);
Log.i("TAG", "newuri " + newuri);
}
c1.close();
break;
}
}
}

Make picture intent failed on Samsung Galaxy I9000

I use the following codes to launch the camera from my app:
private void saveFullImage() {
String storageState = Environment.getExternalStorageState();
if (storageState.equals(Environment.MEDIA_MOUNTED)) {
String path = Environment.getExternalStorageDirectory().getName()
+ File.separatorChar + "Android/data/"
+ RegistrationDetails.this.getPackageName() + "/files/"
+ md5("filedummy") + ".jpg";
File photoFile = new File(path);
try {
if (photoFile.exists() == false) {
photoFile.getParentFile().mkdirs();
photoFile.createNewFile();
}
} catch (IOException e) {
Log.e(TAG, "Could not create file.", e);
}
Log.i(TAG, path);
Uri fileUri = Uri.fromFile(photoFile);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, TAKE_PICTURE);
} else {
new AlertDialog.Builder(this)
.setMessage(
"External Storeage (SD Card) is required.\n\nCurrent state: "
+ storageState).setCancelable(true)
.create().show();
}
}
And I have the following codes in onActivityResult to show that the picture has been taken, so I can proceed the next step:
} else if (requestCode == TAKE_PICTURE) {
if (data == null) {
Toast toast = Toast.makeText(getApplicationContext(),
"Take Picture finished", 10);
toast.show();
}
And I have defined the following settings in AndroidManifest: android.permission.CAMERA and android.permission.WRITE_EXTERNAL_STORAGE
The launch Camera intent works, but when I make a picture and click on Save, then it does not return to onActivityResult and my app crashes.
Can someone help me with this?
Thanks
I got some problems with Galaxy S version 2.3.4 and camera.
After a little work, it actually work with this code (tested with Galaxy S and Nexus S).
You can try it and say me if it works for you.
private Uri mCapturedImageURI;
private void takePhoto() {
String fileName = "temp.jpg";
if (isGalaxyS()) {
fileName = Repertoires_S.getInstance().Get_Photos_Path() + fileName;
File fileTmp = new File(fileName);
if (fileTmp.exists()) fileTmp.delete();
mCapturedImageURI = Uri.fromFile(fileTmp);
} else {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION, "Image prise via XXX :)");
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, PICK_FROM_CAMERA);
}
private boolean isGalaxyS() {
Log.d("Photo", android.os.Build.BRAND + "/" + android.os.Build.PRODUCT + "/"
+ android.os.Build.DEVICE);
ArrayList<String> devices = new ArrayList<String>();
devices.add("samsung/GT-I9000/GT-I9000");
return devices.contains(android.os.Build.BRAND + "/" + android.os.Build.PRODUCT + "/"
+ android.os.Build.DEVICE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case PICK_FROM_CAMERA: {
Bitmap photo = null;
String filenameDest = Repertoires_S.getInstance().Get_Photos_Path() + DateTime_BO_S.getInstance().Date_Courante_AAAAMMJJ_HHMMSS() + ".jpg";
File fDest = new File(filenameDest);
String capturedImageFilePath;
if (data == null) {
// "intent.putExtra(MediaStore.EXTRA_OUTPUT, XXXX);" utilisé
try {
if (isGalaxyS()) {
String fileName = "temp.jpg";
capturedImageFilePath = Repertoires_S.getInstance().Get_Photos_Path() + fileName;
} else {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
capturedImageFilePath = cursor.getString(column_index_data);
}
File fSrc = new File(capturedImageFilePath);
fSrc.renameTo(fDest);
photo = BitmapFactory.decodeFile(filenameDest);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// "intent.putExtra(MediaStore.EXTRA_OUTPUT, XXXX);" non utilisé -> miniature
Bundle extras = data.getExtras();
if (extras != null) {
photo = extras.getParcelable("data");
}
}
if (photo != null) {
try {
int tailleMaxPhoto = 800;
double rap;
int newWidth;
int newHeight;
if (photo.getWidth() > tailleMaxPhoto || photo.getHeight() > tailleMaxPhoto) {
// Si c'est plus grand on redimensionne
if (photo.getWidth() > photo.getHeight()) {
rap = (double)tailleMaxPhoto / photo.getWidth();
newWidth = tailleMaxPhoto;
newHeight = (int)((double)photo.getHeight() * rap);
} else {
rap = (double)tailleMaxPhoto / photo.getHeight();
newHeight = tailleMaxPhoto;
newWidth = (int)((double)photo.getWidth() * rap);
}
Bitmap photoSmall = Bitmap.createScaledBitmap(photo, newWidth, newHeight, true);
if (photoSmall != null) {
FileOutputStream out = new FileOutputStream(filenameDest);
if (photoSmall.compress(Bitmap.CompressFormat.JPEG, 90, out)) {
mPhotosPrat.add(filenameDest);
mPhotoAdapt.notifyDataSetChanged();
}
}
} else {
mPhotosPrat.add(filenameDest);
mPhotoAdapt.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
break;
}
}
}

Categories

Resources