I take a photo and save result in a file. The resulting photo exists, I can open it with file manager. However, I cannot convert that file into a valid Bitmap. I've tried different ways, including BitmapFactory, but it always returns a null Bitmap.
Resulting URI, i.e. mImageUri, is
file:///storage/emulated/0/Pictures/IMG_20150126_180346_1663372760.jpg
and path
/storage/emulated/0/Pictures/IMG_20150126_180346_1663372760.jpg
Code is below.
Utils class to create new image file
public static File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return image;
}
Creating mImageUri in onCreate()
try {
mPhotoFile = Utils.createImageFile();
mImageUri = Uri.fromFile(mPhotoFile);
} catch (IOException ex) {
Toast.makeText(this, getString(R.string.error_something_wrong_happened), Toast.LENGTH_LONG).show();
}
Invoking Camera Intent
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePhotoIntent.resolveActivity(getPackageManager()) != null && mImageUri != null) {
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
startActivityForResult(takePhotoIntent, REQUEST_CAMERA);
}
Parsing results
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
//Unable to get Bitmap from mImageUri
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), mImageUri);
Log.d(TAG, "bitmap exists " + bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Android version is 4.4.4
Maybe is late but I fixed my issue with "bitmap=BitmapFactory.decodeFile(uri);"
The crazy thing is that I didn't need to put "file://" bcos BitmapFactory accept straight way "/storage/emulated/......../bla.jpeg"
Before I was trying to use:
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(uri));
But didn't works....
Related
I'm following android developers guide to capture a high quality image and save it into the storage then display it. The issue is after capturing the image I get redirected to the main activity without displaying the preview though the image was created successfully in the storage
public void take_hq_image(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider", photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, HIGH_Q_IMAGE_CAPTURE_REQUEST);
}
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == HIGH_Q_IMAGE_CAPTURE_REQUEST && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
HQimageView.setImageBitmap(bitmap);
}
}
Saved image path as a string in currentImagePath variable
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
currentImagePath = image.getAbsolutePath();
return image;
}
Then displayed the preview
Bitmap bitmap = BitmapFactory.decodeFile(currentImagePath);
HQimageView.setImageBitmap(bitmap);
I've written some code in a fragment to open the camera app and once a photo is taken, a photo is saved. I cannot get it to save a full size image, its saving a lower res version. Can anyone spot where I've gone wrong?
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
mNewPhotoPath = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES) + "/" +
photoFile.getName();
} catch (IOException ex) {
// Error occurred while creating the File
}
// Continue only if the File was successfully created
if (photoFile != null) {
Uri photoURI = FileProvider.getUriForFile(getContext(),
"com.example.mmackenz.myholidays.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
This is what I have in my onActivityResult in case that is relevant:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
File newImage = new File(mNewPhotoPath);
images.add(newImage);
adapter.notifyDataSetChanged();
Photo newPhoto = new Photo(newImage.getAbsolutePath(), newImage.getName(), -1, -1);
DatabaseHandler db = DatabaseHandler.getInstance(getContext());
db.addPhoto(newImage.getAbsolutePath(), newImage.getName(), -1,-1);
}
}
It adds a new file to an array list which is displayed in a recycler view, and also info of the file in a Photos table.
Thanks
I have a PopupWindow in Android, and inside it I have a imageview. When I press the imageview I want to open the camera take a photo and when I comeback to set photo for imageview's background.
The problem is when I comeback(onActivityResult), the popupwindow is dismiss(), and the imageView background is default.
imageView#onClick:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
createImageFile() function
private File createImageFile() throws IOException {
// Create an image file name
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
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("picture_path", mCurrentPhotoPath);
editor.commit();
return image;
}
#onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
try {
prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
mCurrentPhotoPath = prefs.getString("picture_path", null);
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
add_photo.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I used Sharedpreferences to avoid null on mCurrentPhotoPath .
Assuming the problem is that MediaStore.Images.Media.getBitmap is returning null, it is because it is meant to be used to retrieve an Image from URL handled by some app in some ContentResolver, which is not the case in your implementation.
In your implementation you're storing the image on devices filesystem which you can retrieve with BitmapFactorys decodeFile method that returns the bitmap.
I have a problem, that when i have taken an image from camera, image not displaying in imageview.
I created the code by referring the following link
http://developer.android.com/training/camera/photobasics.html
I am posting my code, please have a look,
public void takeImage(View v) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "sample_" + 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
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
galleryAddPic();
return image;
}
private void galleryAddPic() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(mCurrentPhotoPath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}
}catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
The image captured is storing in SDcard. But not showing in imageview.
Where i have gone wrong. I have tried a lot. But no result. Is there any way to solve this issue.
this works for me:
Bitmap myBitmap = BitmapFactory.decodeFile(imagePath);
image.setImageBitmap(myBitmap);
You don't need to create the temp file, just put the Uri in the intent. After the capture, check the file existence of that Uri. If it exists, capture has been done successfully.
I am trying to get an image taken from the camera, and storing it locally in a cache to preview in an ImageView and upload to a server when needed. The bitmap that I get back is null.
Below is my code:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE){
if (resultCode == RESULT_OK){
// TODO - save the full sized image as well
if(mCurrentPhotoPath!=null){
Log.i(TAG, "Image File found!");
Bitmap imageBitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
if (imageBitmap !=null){
Log.i(TAG, "Successfully retrieved image back.");
}
ImageView postImageView= (ImageView) getActivity().findViewById(R.id.post_image);
postImageView.setImageBitmap(imageBitmap);
}
}
}
}
String mCurrentPhotoPath;
private File createImageCache(Context context) throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = context.getCacheDir();
Log.i(TAG, "StorageDir: "+storageDir);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
Searching around one of the solutions that I found and tried was setting the BitmapFactory.Options, but it didn't work for my case.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Edit: Ran getActivity().getCacheDir().list() and found that the files are indeed saved. Also, here is the button that saves the images:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getActivity().getPackageManager())!=null){
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageCache(getActivity());
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "Error Creating File!!! No Space??");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}else{
Toast.makeText(getActivity(),"Please check your camera", Toast.LENGTH_SHORT).show();
Log.i(TAG, "No camera to run");
}
}
});
and found that the files are indeed saved. Just a list() will not prove that. You created the files yourself so they were there already with length 0. What is the length in bytes afterwards? I think still 0. getCacheDir() delivers internal private memory unreachable for the external picture taker. Try with getExternalCacheDir() instead.