I am trying to Take a Photo with Android Camera Intent as shown in this Tutorial: http://developer.android.com/training/camera/photobasics.html#TaskScalePhoto
The Photo is perfectly taken and is also safed at the given path. But anyway i'm getting following Error:
06-25 14:46:02.228 9070-9070/de.ema.flo.grapp E/BitmapFactory﹕
Unable to decode stream: java.io.FileNotFoundException:
file:/storage/emulated/0/Android/data/de.ema.flo.grapp/files/Pictures/IMG_20150625_144559002.JPG:
open failed: ENOENT (No such file or directory)
Create Image:
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmssSSS").format(new Date());
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = new File(storageDir, "IMG_" + timeStamp + ".JPG");
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
Following code is called after taking the Photo in the Intent
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ACTION_TAKE_PHOTO_B && resultCode == Activity.RESULT_OK) {
if (mCurrentPhotoPath != null) {
ImageView mImageView = (ImageView) getActivity().findViewById(R.id.grillplatz_erstellen_image);
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
// Associate the Bitmap to the ImageView
mImageView.setImageBitmap(bitmap);
mCurrentPhotoPath = null;
}
}
}
I also tried it with this instead. But the result was the same: FileNotFoundException...
try {
InputStream is = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(is);
} catch (FileNotFoundException e) {
e.printStacktrace();
}
Are there any problems with this code? What could I try to change?
Please check the updated code.
private File createImageFile() throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmssSSS").format(new Date());
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
if(!storageDir.isexist)
storageDir.mkdirs();
File image = new File(storageDir, "IMG_" + timeStamp + ".JPG");
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
Let me know if it will help you or not.
Related
I'm taking a screenshot of a dialog and trying to show the image into the gallery. I've saved the image into the external storage but the image is not visible into the gallery. When I go the storage location I can see the latest image there but the image is not showing into the gallery and I've tried multiple codes for this purpose but none work and there is no error as well. Can someone help me with this issue?
Below is the code I'm using to take a screenshot and trying to refresh the gallery:
public void showAlertDialog(final Activity activity) {
Dialog dialog = new Dialog(activity);
currentDialog = dialog;
currentActivity = activity;
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(false);
dialog.setContentView(R.layout.payment_transaction_layout);
ImageView imageViewSS = dialog.findViewById(R.id.imageView19);
imageViewSS.setOnClickListener(v -> {
checkExternalStoragePermission(dialog);
});
dialog.show();
}
private void checkExternalStoragePermission(Dialog dialog) {
if (ContextCompat.checkSelfPermission(currentActivity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(currentActivity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_STORAGE);
} else {
Bitmap bitmap = takeScreenShot(dialog);
saveBitmap(bitmap);
}
}
private static Bitmap takeScreenShot(Dialog dialog) {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
// create bitmap screen capture
View v1 = dialog.getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
return bitmap;
}
public void saveBitmap(Bitmap bitmap) {
File imagePath = currentActivity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File file = null;
try {
/**
*Creating file with the extension file name and given file name
* */
file = File.createTempFile(timeStamp, ".png", imagePath);
Log.e("location", "" + file.getAbsolutePath());
Log.e("TransferClass", "Clicked: " + fromWhere);
saveImageToGallery(bitmap, file);
} catch (IOException e) {
e.printStackTrace();
Log.e("TransferClass", "Exception caught: " + e.getMessage());
}
}
private void saveImageToGallery(Bitmap bitmap, File file) {
FileOutputStream fos;
try {
path = file.getAbsolutePath();
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Log.e("Screenshot", "saved successfully" + " Path " + path);
fos.flush();
fos.close();
//code for showing the image into gallery
currentActivity.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(path)));
} catch (IOException e) {
}
}
This line solve my answer
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, file.getName() ,file.getName());
Copied from Here:
android - save image into gallery
Im building an android app that needs to fetch an image from an url and, after is done displaying it into the image view, I want to store it in the hard drive of the phone so it can be use later without creating a new petition or depending on the cache.
Im using glide 4.9.0
Some of the solutions online include using some deprecated clases such as SimpleTarget and Target that wont be applicable in this project.
This is what I have so far.
File file = new File(holder.context.getExternalFilesDir(null), fileName);
if (file.exists()) {
GlideApp.with(holder.context).load(file).into(holder.ivProductImage);
} else {
GlideApp.with(holder.context).load(urlImage).into(holder.ivProductImage);
// save the image to the hard drive
}
//Step 1
Glide.with(mContext)
.load(images.get(position).getThumbnail())
.asBitmap()
.into(new Target<Bitmap>(100,100) {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
saveImage(resource,position);
}
});
//Step 2
private String saveImage(Bitmap image, int position) {
String savedImagePath = null;
String imageFileName = "JPEG_" + images.get(position).getName() + ".jpg";
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/Comicoid");
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
// Add the image to the system gallery
galleryAddPic(savedImagePath);
}
return savedImagePath;
}
//Step 3
private void galleryAddPic(String imagePath) {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
mContext.sendBroadcast(mediaScanIntent);
}
I'm trying to put the URIs of both the image and the thumbnail from a camera intent into a SQLite database.
I have the full image inserting just fine. I thought I had the thumbnail going in too but it's actually still the full image going into the database again.
Can I get a bit of guidance on how to go about doing this? I've tried a number of things so far but have been stuck for a couple days on this step.
Here are my relevant methods:
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(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
File photoThumbnailFile = null;
try {
photoFile = createImageFile();
photoThumbnailFile = createImageThumbnailFile();
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"com.example.jeremy.sqlwine.fileprovider",
photoFile);
photoThumbnailURI = FileProvider.getUriForFile(this,
"com.example.jeremy.sqlwine.fileprovider",
photoThumbnailFile);
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 = 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;
}
private File createImageThumbnailFile() throws IOException {
// Create an image thumbnail file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageThumbnailFileName = "THUMBNAIL_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageThumbnailFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoThumbnailPath = image.getAbsolutePath();
return image;
}
//This method will happen when the camera is done taking the picture
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Toast.makeText(this, "Image saved", Toast.LENGTH_SHORT).show();
bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), photoURI);
} catch (IOException e) {
e.printStackTrace();
}
bitmapThumbnail = ThumbnailUtils.extractThumbnail(bitmap,50,50);
imageThumbnail.setImageBitmap(bitmapThumbnail);
}
}
I've simple app for capturing image using Camera using following code
#AfterPermissionGranted(RC_STORAGE_PERMS)
private void launchCamera() {
Log.d(TAG, "launchCamera");
// Check that we have permission to read images from external storage.
String perm = android.Manifest.permission.READ_EXTERNAL_STORAGE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
&& !EasyPermissions.hasPermissions(this, perm)) {
EasyPermissions.requestPermissions(this, getString(R.string.rationale_storage),
RC_STORAGE_PERMS, perm);
return;
}
// Create intent
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Choose file storage location
File file = new File(Environment.getExternalStorageDirectory(), UUID.randomUUID().toString() + ".jpg");
mFileUri = Uri.fromFile(file);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mFileUri);
// Launch intent
startActivityForResult(takePictureIntent, RC_TAKE_PICTURE);
}
now I want to upload that image to Firebase storage
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
if (requestCode == RC_TAKE_PICTURE) {
if (resultCode == RESULT_OK) {
if (mFileUri != null) {
uploadFromUri(mFileUri);
} else {
Log.w(TAG, "File URI is null");
}
} else {
Toast.makeText(this, "Taking picture failed.", Toast.LENGTH_SHORT).show();
}
}
}
private void uploadFromUri(Uri fileUri) {
Log.d(TAG, "uploadFromUri:src:" + fileUri.toString());
// [START get_child_ref]
// Get a reference to store file at photos/<FILENAME>.jpg
final StorageReference photoRef = mStorageRef.child("photos")
.child(fileUri.getLastPathSegment());
// [END get_child_ref]
// Upload file to Firebase Storage
// [START_EXCLUDE]
showProgressDialog();
// [END_EXCLUDE]
Log.d(TAG, "uploadFromUri:dst:" + photoRef.getPath());
photoRef.putFile(fileUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Upload succeeded
Log.d(TAG, "uploadFromUri:onSuccess");
// Get the public download URL
mDownloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
Log.w("IMAGE_URL", "Path is " + mDownloadUrl.toString());
uploadedImage = (ImageView) findViewById(R.id.uploaded_img);
try{// Here I'm setting image in ImageView
uploadedImage.setImageURI(mDownloadUrl);
}catch (Exception e){
System.out.print(e.getCause());
}
// [START_EXCLUDE]
hideProgressDialog();
///updateUI(mAuth.getCurrentUser());
// [END_EXCLUDE]
}
})
);
}
in uploadFromUri() at line
try{// Here I'm setting image in ImageView
uploadedImage.setImageURI(mDownloadUrl);
}catch (Exception e){
System.out.print(e.getCause());
}
image is not set in ImageView and I get error
07-29 09:54:23.055 18445-18445/? W/IMAGE_URL: Path is https://firebasestorage.googleapis.com/v0/b/connectin-a74da.appspot.com/o/photos%2F7dd3d46f-ed7b-4020-bc89-fd9e19a8ec65.jpg?alt=media&token=5b4f9ad7-1e99-42b8-966d-50c74fc2eab6
07-29 09:54:23.056 18445-18445/? E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: https:/firebasestorage.googleapis.com/v0/b/connectin-a74da.appspot.com/o/photos%2F7dd3d46f-ed7b-4020-bc89-fd9e19a8ec65.jpg?alt=media&token=5b4f9ad7-1e99-42b8-966d-50c74fc2eab6: open failed: ENOENT (No such file or directory)
and if I open this link I see image there, question is why it is not set in image view
setImageURI() is for content URIs particular to the Android
platform, not URIs specifying Internet resources.
Try getting your bitmap from internet in a new thread an then add it to your ImageView. Like this:
uploadedImage.setImageBitmap(getImageBitmap(mDownloadUrl));
private Bitmap getImageBitmap(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e(TAG, "Error getting bitmap", e);
}
return bm;
}
You also can use a useful library to set image (Internal and external images) called Picasso http://square.github.io/picasso/
Add Picasso library for image loading and use the following code.
Picasso.with(activity).load(imageURL)
.resize(imageWidth,imageHeight)
.into(imageView, new Callback() {
#Override
public void onSuccess() {
Log.d(TAG,"successfully load the image");
}
#Override
public void onError() {
Log.d(TAG,"fail to load the image");
}
});
i'm trying to capture image with android native camera, the save image is good but doesnt contain the usual EXIF data (gps tags, orientation...)
what do i need to do to save also the EXIF?
#Override
public void onClick(View v) {
Intent takePictureIntent = new Intent(android.provider.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) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photoFile));
imageuri = Uri.fromFile(photoFile);
startActivityForResult(takePictureIntent, CAMERA_PIC_REQUEST);
}
}
/*Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);*/
}
}
#SuppressLint("SimpleDateFormat")
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();
return image;
}
Following is the method to Save an Image with EXIF Data (Location Data) to Gallery:
private String saveToGallery (Bitmap bitmapImage){
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to Directory
String photoDir = Environment.getExternalStorageDirectory() + "/" + Environment.DIRECTORY_DCIM + "/";
File directory = new File(photoDir);
// Creates image file with the name "newimage.jpg"
File myfilepath = new File(directory, "newimage.jpg");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myfilepath);
// Use the compress method on the BitMap object to write image to the OutputStream
bitgallery.compress(Bitmap.CompressFormat.JPEG, 80, fos);
fos.flush();
fos.close();
myfilepath.setReadable(true, false);
} catch (Exception e) {
e.printStackTrace();
}
Uri bitmapUri = Uri.fromFile(myfilepath);
String currentImageFile = bitmapUri.getPath();
//Writes Exif Information to the Image
try {
ExifInterfaceEx exif = new ExifInterfaceEx(currentImageFile);
Log.w("Location", String.valueOf(targetLocation));
exif.setLocation(targetLocation);
exif.saveAttributes();
} catch (Exception e) {
e.printStackTrace();
}
// Updating Gallery with the Image (Sending Broadcast to Gallery)
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(currentImageFile);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
return directory.getAbsolutePath();
}
The new image is not parsed, as it should be, by the MediaScanner. This smells like a device-specific bug.
See Image, saved to sdcard, doesn't appear in Android's Gallery app for workarounds.
Here is the function to save the Image,
public static String saveImageInExternalCacheDir(Context context, Bitmap bitmap, String myfileName) {
String fileName = myfileName.replace(' ', '_') + getCurrentDate().toString().replace(' ', '_').replace(":", "_");
String filePath = (context.getExternalCacheDir()).toString() + "/" + fileName + ".jpg";
try {
FileOutputStream fos = new FileOutputStream(new File(filePath));
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, fos);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}