How to convert multiple photos into video using jcodec - java

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.

Related

Webview camera giving an error, creating picture of 0 bytes before taking picture

Those are variables
private static final int FILECHOOSER_RESULTCODE = 1;
private ValueCallback<Uri> mUploadMessage;
private Uri mCapturedImageURI = null;
// the same for Android 5.0 methods only
private ValueCallback<Uri[]> mFilePathCallback;
private String mCameraPhotoPath;
This is the file chooser code
Usually it should create a image after taking the image, but it is creating a blank image before opening the camera intent, and then it is showing an error icon instead of showing the Image.
Please help me to fix the problem
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams) {
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// create the file where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// continue only if the file was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.image_chooser));
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
return true;
}
// creating image files (Lollipop only)
private File createImageFile() throws IOException {
// Create an image file name
Log.d(TAG, "createImageFile: creating Image");
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
mCameraPhotoPath = "file:" + image.getAbsolutePath();
return image;enter code here
}
On Activity Result code given below
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// code for all versions except of Lollipop
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
// retrieve from the private variable if the intent is null
result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e, Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
} // end of code for all versions except of Lollipop
// start of code for Lollipop only
if (requestCode != FILECHOOSER_RESULTCODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null || data.getData() == null) {
// if there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
String dataString = data.getDataString();
if (dataString != null) {
results = new Uri[]{Uri.parse(dataString)};
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
}
Remove this
return File.createTempFile(imageFileName,".jpg",storageDir);
Add this
File image = new File(storageDir.toString()+"/"+imageFileName+".jpg");
return image;
No exercise needed you came here for an answer i presume.

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

Nothing in my ArrayList<Uri>

In my onCreate method, I instantiate an ArrayList:
happyList = new ArrayList<>();
On the click of a button, the following method is called (it should take/pick two pictures):
private void dispatchTakePictureIntent() {
pictureCounter = 0;
for(int i = 0; i < 2; i++) {
pictureCounter++;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
outputFileUri = Uri.fromFile(photoFile);
} catch (IOException ex) {
Log.w("error","IOException");
}catch (NullPointerException nullEx) {
Log.w("error","NullPointerException");
}
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.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(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
startActivityForResult(chooserIntent, REQUEST_TAKE_PHOTO);
}
}
}
And in the onActivityResult, each picture's Uri should be added to the array at the end:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_TAKE_PHOTO) {
final boolean isCamera;
if (data == null) {
isCamera = true;
} else {
final String action = data.getAction();
if (action == null) {
isCamera = false;
} else {
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if (isCamera) {
selectedImageUri = outputFileUri;
} else {
selectedImageUri = data == null ? null : data.getData();
}
// mainView.setImageURI(selectedImageUri);
happyList.add(pictureCounter, selectedImageUri);
}
}
}
I want these URIs in this array so that I can later send the first to an ImageView and be able to 'scroll through' the array to show the next picture in the same ImageView.
When I print out my array however (via ArrayList.toString() method), it is blank. Any idea why this is and how to fix?

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

Null Pointer Exception while taking pictures from camera android HTC

I am using following code to take images from camera or Other intents. On mY Samsung S2 It works fine but HTC Is giving error
private void openImageIntent()
{
// Determine Uri of camera image to save.
final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "OpenionDroid" + File.separator);
root.mkdirs();
final String fname = UUID.randomUUID().toString();
final File sdImageMainDirectory = new File(root, fname);
outputFileUri = Uri.fromFile(sdImageMainDirectory);
// Camera.
final List<Intent> cameraIntents = new ArrayList<Intent>();
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
final PackageManager packageManager = mContext.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(res.activityInfo.packageName, res.activityInfo.name));
intent.setPackage(packageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
cameraIntents.add(intent);
}
// Filesystem.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// Chooser of filesystem options.
final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
// Add the camera options.
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
startActivityForResult(chooserIntent, Constants.IMAGE_REQUEST_CODE);
}
#SuppressWarnings("static-access")
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if(resultCode == mContext.RESULT_OK)
{
if(requestCode == Constants.IMAGE_REQUEST_CODE)
{
final boolean isCamera;
if(data == null)
{
isCamera = true;
}
else
{
final String action = data.getAction();
if(action == null)
{
isCamera = false;
}
else
{
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
}
}
Uri selectedImageUri;
if(isCamera)
selectedImageUri = outputFileUri;
else
selectedImageUri = data == null ? null : data.getData();
if (isPhoto1Selected)
{
photo1Uri = selectedImageUri;
try {
Bitmap bitmap = Utilities.decodeSampledBitmap(Utilities.readBytes(selectedImageUri, mContext), 100, 100);
myQuestion.setLeftThumbnail(Utilities.decodeBitmapToArray(bitmap));
photo1.setImageBitmap(bitmap);
} catch (IOException e) {
Utilities.displayAlert("Oops!", e.getMessage(), mContext);
e.printStackTrace();
}
}
else
{
photo2Uri = selectedImageUri;
try {
Bitmap bitmap = Utilities.decodeSampledBitmap(Utilities.readBytes(selectedImageUri, mContext), 100, 100)
;
myQuestion.setRightThumbnail(Utilities.decodeBitmapToArray(bitmap));
photo2.setImageBitmap(bitmap);
} catch (IOException e) {
Utilities.displayAlert("Oops!", e.getMessage(), mContext);
e.printStackTrace();
}
}
}
}
}
In my code S2 Enters in this
if(data == null)
{
isCamera = true;
}
While HTC goes here
isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
The result isCamera is false. so it tries to run
selectedImageUri = data == null ? null : data.getData();
which gives null
What could be solution, how can i retrieve image from camera?
For HTC Desire, you need some special handling for taking pictures. Here is some code, you will have to adapt it to your needs :
protected static Uri createUriFromPhotoIntentForHtcDesireHD( Activity activity, Intent intent, Uri uri ) {
FileOutputStream fos = null;
try {
Bitmap bitmap = (Bitmap) intent.getExtras().get( "data" );
File outputDir = activity.getCacheDir();
File outputFile = File.createTempFile( "Photo-", ".jpg", outputDir );
fos = new FileOutputStream( outputFile );
bitmap.compress( Bitmap.CompressFormat.JPEG, 90, fos );
uri = Uri.fromFile( outputFile );
} catch ( IOException e ) {
Ln.e( e, "Error creating temp file for HTC Desire HD" );
} finally {
try {
if ( fos != null ) {
fos.close();
}
} catch ( IOException e ) {
Ln.e( e, "Error closing temp file for HTC Desire HD" );
}
}
return uri;
}
If you start an activity to take picture, then in you onActivityResult method, you would expect an intent to contain the uri of the file to download. If it doesn't, then use this code :
Uri uri = intent.getData();
// HTC Desire Bug
if ( uri == null && intent.getExtras() != null && intent.getExtras().get( "data" ) instanceof Bitmap ) {
uri = createUriFromPhotoIntentForHtcDesireHD( activity, intent, uri );
Ln.d( "The intent is %s", intent.getExtras().get( "data" ).getClass().getName() );
}

Categories