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() );
}
Related
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.
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.
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)
{}}
So after trying many answers for the same question, here are just two e.g;
Saving an image in android
and
Saving an image to a server using a Java applet
My app still fails in fact whatever I have done has made it worse, before it would actually save the image as "temp.jpg" in the ExtSD root folder, now when I click the tick to accept the photo nothing happens, no crashing, no nothing, I can retake the image and I can cancel the taking of a photo but nothing else happens.
What it does now:
Opens the camera (or gallery)
Takes the photo
Fails to save/set the photo
What I want it to do;
Take the photo
Store it with a unique name (timestamp)
Have the image set to CircleView
Here is my code (if you need more please ask for what you need);
CircleImageView circleImageView;
ImageButton b;
private void selectImage() {
final CharSequence[] options = { "Take a Pic", "Choose from Gallery", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Set Profile Pic");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals("Take a Pic"))
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
String folder_main = "iDealer";
String sub_folder = "ProPics";
String timeStamp = new SimpleDateFormat("ddMMyyy_HHmmss").format(Calendar.getInstance().getTime());
String pro_pic_name = folder_main + "_" + timeStamp;
File f = new File(android.os.Environment.getExternalStorageDirectory() + "/" + folder_main + "/" + sub_folder + pro_pic_name);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if (options[item].equals("Choose from Gallery"))
{
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else if (options[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
circleImageView.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "iDealer" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);
if (c != null) {
c.moveToFirst();
}
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
Log.w("path from gallery = ", picturePath+"");
circleImageView.setImageBitmap(thumbnail);
}
}
}
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?