Capturing an image and uploading it to a database - java

I want to upload image from camera into database. I already solved the problem from gallery image from gallery already uploaded to database but it wont work on from camera or capture image, i tried to code the same with gallery but i having a error.
Here is my code.
Here is my Android Manifest.xml code
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-feature android:name="android.hardware.camera"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
MainActivity
This is my submit button
reportsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ImageUploadToServerFunction();
}
});
}
This is my code to upload image into database
public void ImageUploadToServerFunction(){
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, bytes);
byte[] byteArrayVar = bytes.toByteArray();
final String ConvertImage = Base64.encodeToString(byteArrayVar, Base64.DEFAULT);
}
This is my code to open open the Camera
private void openCamera() {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
This is my OnActivityResult code
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (attachment >= 1 && attachment <= 8) {
if (resultCode == RESULT_OK && requestCode == 1 && data != null && data.getData() != null) {
Uri uri = data.getData();
try {
if (attachment == 1) {
dynamic = (ImageView) findViewById(R.id.imgview);
} else if (attachment == 2) {
dynamic = (ImageView) findViewById(R.id.imgview1);
} else if (attachment == 3) {
dynamic = (ImageView) findViewById(R.id.imgview2);
} else if (attachment == 4) {
dynamic = (ImageView) findViewById(R.id.imgview3);
} else if (attachment == 5) {
dynamic = (ImageView) findViewById(R.id.imgview4);
} else if (attachment == 6) {
dynamic = (ImageView) findViewById(R.id.imgview5);
} else if (attachment == 7) {
dynamic = (ImageView) findViewById(R.id.imgview6);
} else if (attachment == 8) {
dynamic = (ImageView) findViewById(R.id.imgview7);
}
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
dynamic.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
} else if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
if (attachment == 1) {
dynamic = (ImageView) findViewById(R.id.imgview);
} else if (attachment == 2) {
dynamic = (ImageView) findViewById(R.id.imgview1);
} else if (attachment == 3) {
dynamic = (ImageView) findViewById(R.id.imgview2);
} else if (attachment == 4) {
dynamic = (ImageView) findViewById(R.id.imgview3);
} else if (attachment == 5) {
dynamic = (ImageView) findViewById(R.id.imgview4);
} else if (attachment == 6) {
dynamic = (ImageView) findViewById(R.id.imgview5);
} else if (attachment == 7) {
dynamic = (ImageView) findViewById(R.id.imgview6);
} else if (attachment == 8) {
dynamic = (ImageView) findViewById(R.id.imgview7);
}
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
dynamic.setImageBitmap(imageBitmap);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), imageBitmap);
// CALL THIS METHOD TO GET THE ACTUAL PATH
Toast.makeText(report.this,"Here "+ getRealPathFromURI(tempUri),Toast.LENGTH_LONG).show();
}
System.out.print(resultCode);
}
}
public 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 String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}

Related

Pickup image from gallery in android 11 + (Access denid)

Despite getting the necessary access to the file in Android, when I select a photo from the gallery in Android 11 and above, Android shows the message access denied.
I just select the image and receive it as a bitmap.
I try thease
1
...
Manifest permissions:
<uses-permission android:name="android.permission.READ_MEDIA_IMAGES" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"
android:maxSdkVersion="32" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="29" />
Select image from gallery:
public void selectImageFromGallery(ImageView view) {
setResourceImg(view);
checkListener();
if (tempFileFromSource == null) {
try {
tempFileFromSource = File.createTempFile("choose", "png", mContext.getExternalCacheDir());
tempUriFromSource = Uri.fromFile(tempFileFromSource);
} catch (IOException e) {
e.printStackTrace();
}
}
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUriFromSource);
if (fragment == null) {
mContext.startActivityForResult(intent, REQUEST_PICTURE_FROM_GALLERY);
} else {
fragment.startActivityForResult(intent, REQUEST_PICTURE_FROM_GALLERY);
}
}
On Activity Result:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((requestCode == REQUEST_PICTURE_FROM_GALLERY) && (resultCode == Activity.RESULT_OK)) {
Log.d(TAG, "Image selected from gallery");
imageActionListener.onImageSelectedFromGallery(data.getData(), tempFileFromSource);
} else if ((requestCode == REQUEST_PICTURE_FROM_CAMERA) && (resultCode == Activity.RESULT_OK)) {
Log.d(TAG, "Image selected from camera");
imageActionListener.onImageTakenFromCamera(tempUriFromSource, tempFileFromSource);
} else if ((requestCode == REQUEST_CROP_PICTURE) && (resultCode == Activity.RESULT_OK)) {
Toast.makeText(mContext, "uryyg: "+data.toString(), Toast.LENGTH_SHORT).show();
Log.d(TAG, "Image returned from crop");
imageActionListener.onImageCropped(tempUriFromCrop, tempFileFromCrop);
}
}
Crop selected image:
public void requestCropImage(Uri uri, int outputX, int outputY, int aspectX, int aspectY) {
checkListener();
if (tempFileFromCrop == null) {
try {
tempFileFromCrop = File.createTempFile("crop", "png", mContext.getExternalCacheDir());
tempUriFromCrop = Uri.fromFile(tempFileFromCrop);
} catch (IOException e) {
e.printStackTrace();
}
}
// open crop intent when user selects image
final Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(uri, "image/*");
intent.putExtra("output", tempUriFromCrop);
intent.putExtra("outputX", outputX);
intent.putExtra("outputY", outputY);
intent.putExtra("aspectX", aspectX);
intent.putExtra("aspectY", aspectY);
intent.putExtra("scale", true);
intent.putExtra("noFaceDetection", true);
if (fragment == null) {
mContext.startActivityForResult(intent, REQUEST_CROP_PICTURE);
} else {
fragment.startActivityForResult(intent, REQUEST_CROP_PICTURE);
}
//Toast.makeText(mContext, "uri3: "+uri.toString(), Toast.LENGTH_SHORT).show();
}
And we return the uri of the cropped image in the cache to this method:
#Override
public void onImageCropped(Uri uri, File imageFile) {
try {
Uri selectedImage = uri;
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
// getting bitmap from uri
//Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
Bitmap bitmap = BitmapFactory.decodeFile(picturePath);
} catch (Exception e) {
e.printStackTrace();
}
}
You will need to use intent with an action set to Intent.ACTION_GET_CONTENT and set the type of this intent to match all the image files i.e. "image/*". If you want that user will able to select only specific image file formats like png or jpeg then use something like "image/png" or "image/jpeg".
The code below describes a fully working example that is tested on Android 12L.
Create intent like this
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
pickerActivityResultLauncher.launch(Intent.createChooser(intent, "Select a photo"));
Using the AndroidX activity result register
private ActivityResultLauncher<Intent> pickerActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == RESULT_OK) {
// This is the URI for the selected photo from the user.
Uri photoUri = result.getData().getData();
// Set URI to the image view to display the image.
imageView.setImageURI(photoUri);
} else {
// Handle the no-image selection case.
}
});
If you want to use the old method (which has no guarantee that it works on every device) then you can use
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select a photo"), REQUEST_PICTURE_FROM_GALLERY)

How to convert multiple photos into video using jcodec

I have three photos that are entered by the user
using a camera or gallery I have saved the photos that the user takes with this code
private void openImageIntent(int type) {
// Determine Uri of camera image to save.
final File root = new File(
Environment.getExternalStorageDirectory() + File.separator + "myapp" + File.separator);
boolean success = root.exists() || root.mkdir();
if (success) {
final String fName = "img_" + System.currentTimeMillis() + ".jpg";
outputFileUri = Uri.fromFile(new File(root, fName));
// Camera.
final List<Intent> cameraIntents = new ArrayList<>();
final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = getPackageManager();
final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
for (ResolveInfo res : listCam) {
final String packageName = res.activityInfo.packageName;
final Intent intent = new Intent(captureIntent);
intent.setComponent(new ComponentName(packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
// Chooser of filesystem options.
Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.Select_image));
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
startActivityForResult(chooserIntent, type);
} else {
// Filesystem.
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
// Chooser of filesystem options.
Intent chooserIntent = Intent.createChooser(galleryIntent, getString(R.string.Select_image));
startActivityForResult(chooserIntent, type);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == RESULT_OK) {
// Select Image from Camera Or Gallery
if (requestCode == 1) {
final boolean isCamera;
if (data == null) {
// Camera
isCamera = true;
} else {
String action = data.getAction();
if (action == null) {
// Gallery
isCamera = false;
} else {
// Camera OR Gallery
isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri = isCamera ? outputFileUri : data.getData();
if (selectedImageUri != null) {
// Start Cropping Image Calendar.getInstance().getTime()
String destinationFileName = "SampleCropImage_" + System.currentTimeMillis() + ".png";
Uri outputCropImageUri = Uri.fromFile(new File(getCacheDir(), destinationFileName));
UCrop uCrop = UCrop.of(selectedImageUri, outputCropImageUri);
uCrop.withOptions(getUCropOptions(this));
uCrop.start(this);
} else
ShowMessage("ERORR");
} else if (requestCode == 2) {
final boolean isCamera;
if (data == null) {
// Camera
isCamera = true;
} else {
String action = data.getAction();
if (action == null) {
// Gallery
isCamera = false;
} else {
// Camera OR Gallery
isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri = isCamera ? outputFileUri : data.getData();
if (selectedImageUri != null) {
// Start Cropping Image Calendar.getInstance().getTime()
String destinationFileName = "SampleCropImage_" + System.currentTimeMillis() + ".png";
Uri outputCropImageUri = Uri.fromFile(new File(getCacheDir(), destinationFileName));
UCrop uCrop = UCrop.of(selectedImageUri, outputCropImageUri);
uCrop.withOptions(getUCropOptions(this));
uCrop.start(this);
} else
ShowMessage("ERORR");
} else if (requestCode == 3) {
final boolean isCamera;
if (data == null) {
// Camera
isCamera = true;
} else {
String action = data.getAction();
if (action == null) {
// Gallery
isCamera = false;
} else {
// Camera OR Gallery
isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri = isCamera ? outputFileUri : data.getData();
if (selectedImageUri != null) {
// Start Cropping Image Calendar.getInstance().getTime()
String destinationFileName = "SampleCropImage_" + System.currentTimeMillis() + ".png";
Uri outputCropImageUri = Uri.fromFile(new File(getCacheDir(), destinationFileName));
UCrop uCrop = UCrop.of(selectedImageUri, outputCropImageUri);
uCrop.withOptions(getUCropOptions(this));
uCrop.start(this);
} else
ShowMessage("ERORR");
}
// Crop Result
if (requestCode == UCrop.REQUEST_CROP && type == 1) {
Uri resultUri = UCrop.getOutput(data);
if (resultUri != null) {
byte[] imageByte = ImageUtils.compressImage(this, resultUri);
Bitmap bitmap = ImageUtils.getBitmapFromByte(imageByte);
Image1.setImageBitmap(bitmap);
} else
ShowMessage("ERORR");
} else if (requestCode == UCrop.REQUEST_CROP && type == 2) {
Uri resultUri = UCrop.getOutput(data);
if (resultUri != null) {
byte[] imageByte = ImageUtils.compressImage(this, resultUri);
Bitmap bitmap = ImageUtils.getBitmapFromByte(imageByte);
Image2.setImageBitmap(bitmap);
} else
ShowMessage("ERORR");
} else if (requestCode == UCrop.REQUEST_CROP && type == 3) {
Uri resultUri = UCrop.getOutput(data);
if (resultUri != null) {
byte[] imageByte = ImageUtils.compressImage(this, resultUri);
Bitmap bitmap = ImageUtils.getBitmapFromByte(imageByte);
Image3.setImageBitmap(bitmap);
} else
ShowMessage("ERORR");
}
}
if (resultCode == UCrop.RESULT_ERROR) {
final Throwable cropError = UCrop.getError(data);
if (cropError != null)
Toast.makeText(this, cropError.getMessage(), Toast.LENGTH_LONG).show();
else
ShowMessage("Erorr");
}
} catch (Exception e) {
e.printStackTrace();
}
}
How do I make these images that were entered by the user turn into a video using jcodec library ?
Please, I need a code that matches my code When I paste it works I am a beginner, I searched a lot and found many solutions but it is not at all clear to me
How do I make these images that were entered by the user turn into a video using jcodec library ?
Thanks <3.

OnActivityResult: Uri and getData is a null object during capture a photo

I have a problem with Uri object. User should take a photo and next this is sending to Firebase Storage. But sth is wrong with onActivityResult.
I read a lot of topics (https://developer.android.com/training/camera/photobasics.html, StackOverFlow too) but nothing works with this code.
There is an error:
Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
Below is a code:
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
}
});
}
}
}
As I checked, data (Intent) in onActivityResult is equal to NULL, so uri is null as well.
So, how can I resolve this challenge and make it usable? Should I use a Bitmap to have an access to a photo?
Could someone help me to resolve this situation?
Regards
I figured out with my question.
It works at now.
private ProgressDialog mProgress;
private Button mUploadBtn;
private ImageView mImageView;
Uri picUri;
private StorageReference mStorage;
private static final int CAMERA_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mUploadBtn = (Button) findViewById(R.id.uploadBtn);
mImageView = (ImageView) findViewById(R.id.imageView);
mProgress = new ProgressDialog(this);
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file=getOutputMediaFile(1);
picUri = Uri.fromFile(file); // create
i.putExtra(MediaStore.EXTRA_OUTPUT,picUri); // set the image file
startActivityForResult(i, CAMERA_REQUEST_CODE);
}
});
}
/** Create a File for saving an image */
private File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyApplication");
/**Create the storage directory if it does not exist*/
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
/**Create a media file name*/
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == 1){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".png");
} else {
return null;
}
return mediaFile;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK ) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = picUri;
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
}
});
}
}
Always create your file and store the captured image using the path as follows
File photoFile = null;
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
});
}
private File createImageFile() throws IOException {
// Create an image mSelectedFile name
String timeStamp = new SimpleDateFormat(Constants.PHOTO_DATE_FORMAT, Locale.ENGLISH).format(new Date());
String imageFileName = "IMG_" + timeStamp;
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return file;
}
Then use this file "photoFile" and use it as needed in onActivityResult.
I faced the same problem before so i made sure that i check everything i can check when onActivityResult is called below is my code.
First i use this intent to capture image
File photoFile;
URI uri;
mUploadBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePhotoIntent.resolveActivity(getPackageManager()) != null)
{
try
{
photoFile = Create_ImageFile();
}
catch (Exception e)
{
Log.e("file", e.toString());
}
if (photoFile != null)
{
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile.getAbsoluteFile()));
}
}
startActivityForResult(takePhotoIntent, CAMERA_REQUEST_CODE);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
{
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case CAMERA_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK)
{
try
{
Uri selectedImageURI = null;
ByteArrayOutputStream bos;
Bitmap bitmap = null;
int orientation;
ExifInterface exif = null;
FileOutputStream fos = null;
bos = new ByteArrayOutputStream();
try
{
uri=imageReturnedIntent.getData();
selectedImageURI = imageReturnedIntent.getData();
bitmap= BitmapFactory.decodeFile(GetRealPathFromURI(selectedImageURI));
exif = new ExifInterface(GetRealPathFromURI(selectedImageURI));
fos = new FileOutputStream(GetRealPathFromURI(selectedImageURI));
}
catch (Exception e)
{
e.printStackTrace();
}
if(bitmap==null)
{
uri=Uri.fromFile(photoFile.getAbsoluteFile()));
bitmap=BitmapFactory.decodeFile(photoFile.getAbsolutePath());
exif = new ExifInterface(photoFile.getAbsolutePath());
fos = new FileOutputStream(photoFile.getAbsolutePath());
}
if(bitmap==null)
{
String imagePath = getPathGalleryImage(imageReturnedIntent);
bitmap = BitmapFactory.decodeFile(imagePath);
exif = new ExifInterface(imagePath);
fos = new FileOutputStream(imagePath);
}
Log.e("PhotoFile",photoFile.getAbsolutePath());
// Bitmap bitmap =(Bitmap) imageReturnedIntent.getExtras().get("data");
//bitmap = Bitmap.createScaledBitmap(bitmap,bitmap.getWidth(),bitmap.getHeight(), false);
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Log.e("ExifInteface .........", "rotation ="+orientation);
//exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);
Log.e("orientation", "" + orientation);
Matrix m = new Matrix();
if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
m.postRotate(180);
//m.postScale((float) bm.getWidth(), (float) bm.getHeight());
// if(m.preRotate(90)){
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
m.postRotate(90);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
{
m.postRotate(270);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
else
{
m.postRotate(0);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
//CropImage.activity(selectedImageURI).setGuidelines(CropImageView.Guidelines.ON).start(this);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
userProfileIMG.setImageBitmap(bitmap);
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
}
catch (Exception e)
{
e.printStackTrace();
}
}
break;
}
}
private String getPathGalleryImage(Intent imageURI)
{
Uri selectedImage = imageURI.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 imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}
/**
* When image is returned we get its real path
**/
private String GetRealPathFromURI(Uri contentURI)
{
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
// Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private File Create_ImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp;
File mediaStorageDir = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = new File(mediaStorageDir.getAbsolutePath() + File.separator + imageFileName);
return image;
}
after this process i always ended having a bitmap to use it as i want.
For Get Actual Image predefined path of Captured Image using
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
this.startActivityForResult(cameraIntent, 101);
After Captured Image you can get Captured Image on path which is set in cameraIntent. If you don't Want to set predefined path then check Intent data.
if (resultCode == android.app.Activity.RESULT_OK && requestCode == 101) {
try {
path_mm = "Onsuccess_resultcode";
generateNoteOnSD("photo34.txt", path_mm);
Bitmap photo = null;
if (data == null) {
//get Bitmap here.
}
else {
Uri u1 = data.getData();
//get uri and find actual path on that uri.
}
}catch(Exception ex)
{}}

How to set different request codes in onActivityResult?

I have an app that chooses a picture either from gallery or from camera and put it on an imageview. The problem is that I can't set two different request codes for the same OnActivityResult.
camera capture works, but gallery doesn't. I get this:
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://media/external/images/media/272 flg=0x1 }} to activity {com.parse.starter/com.parse.starter.reportar}: java.lang.NullPointerException: uriString
at android.app.ActivityThread.deliverResults(ActivityThread.java:3649)
Could someone help me please?? here is my code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Image from gallery...
if(requestCode == 1 && resultCode == RESULT_OK && data !=null){
Uri selectedImage = data.getData();
try {
//converts data into bitmap
Bitmap bitmapImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
//sets image on imageview
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(bitmapImage);
} catch (IOException e){
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(),"Error", Toast.LENGTH_LONG).show();
}
}
//Image from camera
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplication().getBaseContext(),"Error", Toast.LENGTH_LONG).show();
}
}
}
Try this
private int LOAD_IMAGE_RESULTS=1;
OnChoose Code
chooseimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= 23){
boolean result= Utility.checkPermission(getActivity());
if(result) {
galleryIntent();
}
}
else {
Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start new activity with the LOAD_IMAGE_RESULTS to handle back the results when image is picked from the Image Gallery.
startActivityForResult(i,LOAD_IMAGE_RESULTS); //LOAD_IMAGE_RESULTS
}
}
});
Also Code added For Permission and Set Image
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= 23) {
if (resultCode == Activity.RESULT_OK) {
if (requestCode == LOAD_IMAGE_RESULTS) {
onSelectFromGalleryResult(data);
}
}
}
else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {
Bitmap bitmap = null;
Uri selectedImage = data.getData();
String wholeID = DocumentsContract.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
//filePath = cursor.getString(columnIndex);
mPath = cursor.getString(columnIndex);
}
cursor.close();
}
else {
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == getActivity().RESULT_OK && data != null) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
mPath = cursor.getString(cursor.getColumnIndex(filePath[0]));
//edAttach.setText(mPath.toString()); path set anywhere
cursor.close();
}
}
}
}
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
ivprofile.setImageBitmap(bm);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && isMediaDocument(data.getData())) {
Uri selectedImage = data.getData();
String wholeID = DocumentsContract.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getActivity().getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
//filePath = cursor.getString(columnIndex);
mPath = cursor.getString(columnIndex);
//edAttach.setText(mPath); path set anywhere
}
cursor.close();
}
else {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mPath = cursor.getString(columnIndex).toString();
System.out.println("picturePath" + mPath);
if (!mPath.equalsIgnoreCase(null)) {
edAttach.setText(mPath);
}
cursor.close();
}
}
public boolean hasPermissionInManifest(Context context, String permissionName) {
final String packageName = context.getPackageName();
try {
final PackageInfo packageInfo = context.getPackageManager()
.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
final String[] declaredPermisisons = packageInfo.requestedPermissions;
if (declaredPermisisons != null && declaredPermisisons.length > 0) {
for (String p : declaredPermisisons) {
if (p.equals(permissionName)) {
return true;
}
}
}
} catch (PackageManager.NameNotFoundException e) {
}
return false;
}
public static boolean isMediaDocument(Uri uri)
{
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private void galleryIntent()
{
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);//
startActivityForResult(Intent.createChooser(intent, "Select File"),LOAD_IMAGE_RESULTS);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
galleryIntent();
} else {
//code for deny
}
break;
}
}
Or Permission In your mainfiest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

intent camera crashes after back press

I am trying to use intent camera to capture video in my app,when i take a video and i am redirected to the Main activity it works all fine,however after i press back button in the intent camera mode it crashes
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
protected void onActivityResult(int reqCode, int resCode, Intent data) {
if (reqCode == REQUEST_CODE_UPDATE_PIC) {
if (resCode == RESULT_OK) {
String imagePath = data.getStringExtra(GOTOConstants.IntentExtras.IMAGE_PATH);
showCroppedImage(imagePath);
Bitmap bitmap;
bitmap = BitmapFactory.decodeFile(imagePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] image = stream.toByteArray();
// Create the ParseFile
ParseFile file = new ParseFile("profilepic.png", image);
// Upload the image into Parse Cloud
file.saveInBackground();
// Create a column named "ImageFile" and insert the image
user.put("profilepictures", file);
user.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Toast.makeText(getApplicationContext(), "Saved Successfully",
Toast.LENGTH_SHORT).show();
}
});
// Show a simple toast message
Toast.makeText(MainActivity.this, "Image Uploaded",
Toast.LENGTH_SHORT).show();
} else if (resCode == RESULT_CANCELED) {
//TODO : Handle case
} else {
String errorMsg = data.getStringExtra(ImageCropActivity.ERROR_MSG);
Toast.makeText(this, errorMsg, Toast.LENGTH_LONG).show();
}
}
if (mediaFile != null) {
compress();
}
if (resCode == Activity.RESULT_OK && data != null) {
uri = data.getData();
if (uri == null) {
Toast.makeText(getApplicationContext(), "uri blank", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "uri full", Toast.LENGTH_LONG).show();
}
//proceedbutton.setVisibility(View.VISIBLE);
if (resCode == RESULT_CODE_COMPRESS_VIDEO) {
if (uri != null) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
String displayName = cursor.getString(
cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Log.i(TAG, "Display Name: " + displayName);
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
String size = null;
if (!cursor.isNull(sizeIndex)) {
size = cursor.getString(sizeIndex);
} else {
size = "Unknown";
}
Log.i(TAG, "Size: " + size);
tempFile = FileUtils.saveTempFile(displayName, this, uri);
editText.setText(mediaFile.getPath());
}
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}
}
}
I am guessing if your Camera Video Intent CODE = RESULT_CODE_COMPRESS_VIDEO. Then replace your code as below to
First Thing change resCode == RESULT_CODE_COMPRESS_VIDEO.to reqCOde and use the following code
if (reqCode == RESULT_CODE_COMPRESS_VIDEO) {
if(resCode == RESULT_OK) {
if (uri != null) {
compress();
}
}
else if(resCode == RESULT_CANCELED && data!=null){
Toast.makeText(MainActivity.this,"No Video Recorded",Toast.LENGTH_SHORT).show();
}
}
This won't crash your application on backpressed from the intent camera.
Hope this helps !
if (reqCode == RESULT_CODE_COMPRESS_VIDEO) {
if(resCode == RESULT_OK) {
if (uri != null) {
compress();
}
}
else if(resCode == RESULT_CANCELED && data!=null){
Toast.makeText(MainActivity.this,"Error !",Toast.LENGTH_LONG).show();
else return true;
}
}
if (requestCode == 1) {
if(data !=null){
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
//String path = saveImage(thumbnail);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
Glide.with(eventPreview.getContext()).load(byteArray).into(eventPreview);
int width = eventPreview.getMeasuredWidth();
eventPreview.getLayoutParams().height = width/2;
eventPreview.setScaleType(ImageView.ScaleType.FIT_XY);
postData = byteArray;
PreviewTXT.setVisibility(View.GONE);}
}

Categories