I take a photo and save it to external storage :
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photoFile = getPhotoFile();
String authorities = getActivity().getPackageName() + ".fileprovider";
imageUri = FileProvider.getUriForFile(getActivity(), authorities, photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, 1);
It works fine
But what about recording a video
I wrote some code like this but i think it's not correct :
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
File videoFile = getVideoFile();
String authorities = getActivity().getPackageName() + ".fileprovider";
videoUri = FileProvider.getUriForFile(getActivity(), authorities, videoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
startActivityForResult(intent, 2);
What can i do?
EDIT:
And these methods create a dir and return photo and video files
public File getPhotoFile() {
//create a random name
String randomName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File mainPath = new File(path, "/Images");
if (!mainPath.exists()) {
mainPath.mkdirs();
}
File photoPath = new File(mainPath, randomName + ".jpg");
return photoPath;
}
public File getVideoFile() {
//create a random name
String randomName = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
File mainPath = new File(path, "/Videos");
if (!mainPath.exists()) {
mainPath.mkdirs();
}
File photoPath = new File(mainPath, randomName + ".mp4");
return photoPath;
}
To record video use:
startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
Here is an example
in your recordVideo.onClick() method add this code
if (checkPermissions(YourActivity.this)) {
captureVideo();
} else {
requestCameraPermission(MEDIA_TYPE_VIDEO);
}
public static boolean checkPermissions(Context context) {
return ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) ==
PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context,
Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(context,
Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
}
//in CaptureVideo method
private void captureVideo() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
File file = getOutputMediaFile(MEDIA_TYPE_VIDEO);
if (file != null) {
imageStoragePath = file.getAbsolutePath();
}
Uri fileUri = getOutputMediaFileUri(getApplicationContext(), file);
// set video quality
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
// start the video capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}
/**
* Creates and returns the image or video file before opening the camera
*/
public static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
YourActivity.GALLERY_DIRECTORY_NAME);
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e(YourActivity.GALLERY_DIRECTORY_NAME, "Oops! Failed create "
+ YourActivity.GALLERY_DIRECTORY_NAME + " directory");
return null;
}
}
public static Uri getOutputMediaFileUri(Context context, File file) {
return FileProvider.getUriForFile(YourActivity.this, context.getPackageName() +
".provider", file);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Refreshing the gallery
refreshGallery(getApplicationContext(), imageStoragePath);
// video successfully recorded
showVideo();
} else if (resultCode == RESULT_CANCELED) {
// user cancelled recording
Toast.makeText(getApplicationContext(),
"cancelled video recording", Toast.LENGTH_SHORT)
.show();
} else {
// failed to record video
Toast.makeText(getApplicationContext(),
"Sorry! Failed to record video", Toast.LENGTH_SHORT)
.show();
}
}
}
public static void refreshGallery(Context context, String filePath) {
// ScanFile so it will be appeared on Gallery
MediaScannerConnection.scanFile(context,
new String[]{filePath}, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
}
private void showVideo() {
try {
videoView.setVideoPath(imageStoragePath);
// video playing
videoView.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Related
As per android R privacy policy changes, I want to perform the capture and crop image feature for android R devices. I tried the below method but it saving the empty file (file is creating in a specified folder but having a size of 0kb).
I'm using Android-image-cropper library to crop images.
public static File createImageFile(Context context) throws IOException {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp + ".jpg";
File storageDir, image;
if(SDK_INT >= Build.VERSION_CODES.Q){
OutputStream outputStream;
ContentResolver contentResolver = context.getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, imageFileName);
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + File.separator + SD_FOLDER_NAME);
Uri imageUri = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
outputStream = contentResolver.openOutputStream(Objects.requireNonNull(imageUri));
Objects.requireNonNull(outputStream);
storageDir = new File(Environment.DIRECTORY_PICTURES + File.separator + SD_FOLDER_NAME);
}else{
storageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + SD_FOLDER_NAME);
}
if (!storageDir.exists()) {
storageDir.mkdirs();
}
image = new File(storageDir, imageFileName);
if (image.createNewFile()) {
Log.d(TAG, ":Image file created");
} else {
Log.d(TAG, ":Image file not created");
}
return image;
}
Below are my camera open and capture functions:
private void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri photoURI = null;
try {
fileUri = Utils.createImageFile(requireContext());
if(SDK_INT >= Build.VERSION_CODES.Q)
photoURI = FileProvider.getUriForFile(requireActivity(), requireActivity().getPackageName(), fileUri);
else
photoURI = FileProvider.getUriForFile(requireActivity(), requireActivity().getPackageName() + ".com.enrich.salonapp.provider", fileUri);
} catch (IOException e) {
e.printStackTrace();
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(intent, REQUEST_CODE_CAMERA_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PictureSelectorDialog.REQUEST_CODE_CAMERA_PICTURE && resultCode == Activity.RESULT_OK) {
imageCapture.onImageCaptured(fileUri.getAbsolutePath(), false);
} else if (requestCode == PictureSelectorDialog.REQUEST_CODE_GALLERY_PICTURE && resultCode == Activity.RESULT_OK) {
if (FileUtils.getPath(getActivity(), data.getData()) == null) {
imageCapture.onImageCaptured(data.getData().toString(), true);
} else {
imageCapture.onImageCaptured(FileUtils.getPath(getActivity(), data.getData()), false);
}
}
this.dismissAllowingStateLoss();
}
Also, I didn't found how to get URI using file provider.
if(SDK_INT >= Build.VERSION_CODES.Q)
photoURI = FileProvider.getUriForFile(requireActivity(), requireActivity().getPackageName(), fileUri);
After seeing multiple answers, developer docs, and many more. I ended up with this below working solution, Hope this will help someone.
AndroidManifest
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="29"/>
android:requestLegacyExternalStorage="true"
<provider
android:name=".util.GenericFileProvider"
android:authorities="${applicationId}.provider.profile"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/provider_paths"/>
</provider>
PictureSelectorDialog.java
public static final int REQUEST_CODE_CAMERA_PICTURE = 1232;
public static final int REQUEST_CODE_GALLERY_PICTURE = 1233;
private File fileUri;
private ImageCapture imageCapture;
private boolean isDenied = false;
private void openGallery() {
Intent intent;
intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(Intent.createChooser(intent, getString(R.string.choose_from_gallery)), REQUEST_CODE_GALLERY_PICTURE);
}
private void openCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri photoURI = null;
try {
fileUri = Utils.createImageFile(requireContext());
photoURI = FileProvider.getUriForFile(requireContext(), BuildConfig.APPLICATION_ID + ".provider.profile", fileUri);
} catch (IOException e) {
e.printStackTrace();
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(intent, REQUEST_CODE_CAMERA_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PictureSelectorDialog.REQUEST_CODE_CAMERA_PICTURE && resultCode == Activity.RESULT_OK) {
imageCapture.onImageCaptured(fileUri.getAbsolutePath(), false);
} else if (requestCode == PictureSelectorDialog.REQUEST_CODE_GALLERY_PICTURE && resultCode == Activity.RESULT_OK) {
if (FileUtils.getPath(getActivity(), data.getData()) == null) {
Uri uri = data.getData();
ParcelFileDescriptor parcelFileDescriptor;
try {
parcelFileDescriptor = requireContext().getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
File tempFile = createImageFile(requireContext());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100 , bos);
byte[] bitmapData = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(tempFile);
fos.write(bitmapData);
imageCapture.onImageCaptured( tempFile.getAbsolutePath(), true);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
imageCapture.onImageCaptured(FileUtils.getPath(getActivity(), data.getData()), false);
}
}
this.dismissAllowingStateLoss();
}
public interface ImageCapture {
void onImageCaptured(String path, boolean isGooglePhotoURI);
}
Utils.java
public static File createImageFile(Context context) throws IOException {
String timeStamp = new SimpleDateFormat(YYYY_MM_DD_HH_MM_SS_FOR_IMAGE_NAMING, Locale.getDefault()).format(new Date());
String imageFileName = "PROFILE_PICTURE_" + timeStamp;
File image, storageDir;
if (SDK_INT < Build.VERSION_CODES.Q) {
storageDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + YOUR_FOLDER_NAME);
if (!storageDir.exists()) {
storageDir.mkdirs();
}
image = new File(storageDir, imageFileName + ".jpg");
image.createNewFile();
} else {
storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES + File.separator + YOUR_FOLDER_NAME);
image = File.createTempFile(imageFileName, ".jpg", storageDir);
String currentPhotoPath = image.getAbsolutePath();
}
return image;
}
So i have 2 Activities, the first one is to launch camera before the second Activity start. After taking the camera, the ImageView on second Activities will changed by the photo ive taken. And if i click the ImageView, it will intent the camera and replacing the image from camera. However, i cant replace the image at ImageView and the resultCode always 0 everytime after taking picture.
here is first Activity
#OnClick(R.id.fab_toko)
private void create_ticket() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(Consts.MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
startActivityForResult(intent, Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
//return FileProvider.getUriForFile(MainActivity.this, MainActivity.this.getApplicationContext().getPackageName(), getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Consts.IMAGE_DIRECTORY_NAME);
//Creating an internal dir;
File mDir = RumahkeduaApplication.getContext().getDir("ISS", Context.MODE_PRIVATE);
//Internal Storage
// File mediaInternalDir = new File(mDir,Consts.IMAGE_DIRECTORY_NAME);
File mediaInternalDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
// Create the storage directory if it does not exist
if (!mediaInternalDir.exists()) {
if (!mediaInternalDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Consts.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == Consts.MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaInternalDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
if (requestCode == Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
comImage.compressImage(fileUri.toString());
Intent mainIntent = new Intent(MainActivity.this, CreateTicketActivity.class);
mainIntent.putExtra("id_user", login_user.getId_user());
mainIntent.putExtra("string_uri", fileUri.toString());
mainIntent.putExtra("ticket_type", "Toko Prima");
MainActivity.this.startActivity(mainIntent);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
}
And here is second Activity
#OnClick(R.id.iv_post_photo)
private void captureImage() {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
// if (!ticket_type.equals("Toko Prima")){
// TODO
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(Consts.MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
// start the image capture Intent
startActivityForResult(intent, Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
setResult(RESULT_OK);
// }
}
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
Consts.IMAGE_DIRECTORY_NAME);
File mediaInternalDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
// Create the storage directory if it does not exist
if (!mediaInternalDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ Consts.IMAGE_DIRECTORY_NAME + " directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(new Date());
File mediaFile;
if (type == Consts.MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
} else {
return null;
}
return mediaFile;
}
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
outState.putParcelable("file_uri", fileUri);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// if the result is capturing Image
// ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
if (requestCode == Consts.CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// successfully captured the image
comImage.compressImage(fileUri.toString());
Picasso.with(this).load(fileUri).fit().centerCrop().into(ivPhoto);
} else if (resultCode == RESULT_CANCELED) {
// user cancelled Image capture0
Toast.makeText(getApplicationContext(),
"User cancelled image capture", Toast.LENGTH_SHORT)
.show();
} else {
// failed to capture image
Toast.makeText(getApplicationContext(),
"Sorry! Failed to capture image", Toast.LENGTH_SHORT)
.show();
}
}
storage permission already checked on manifest
i used a combination of answers to make it work so i ended up with this code:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Date dat = Calendar.getInstance().getTime();
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-mm-dd-hh:mm:ss");
String nameFoto = simpleDate.format(dat) + ".png";
String filename = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+ File.separator +nameFoto;
File ff = new File(filename);
try {
ff.createNewFile();
//imageUri = Uri.fromFile(ff);
imageUri = FileProvider.getUriForFile(IngresarFactura.this, BuildConfig.APPLICATION_ID + ".provider",ff);
//imageUri = new Uri(filename).
if (imageUri.getPath() == null){
mensaje.setText(filename+ " Error path es nulo.");
}
cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageUri);
//COMPATIBILITY
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.LOLLIPOP) {
cameraIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
} else {
List<ResolveInfo> resInfoList = IngresarFactura.this.getPackageManager().queryIntentActivities(cameraIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
IngresarFactura.this.grantUriPermission(packageName, imageUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
//COMPATIBILITY
activityResultLaunch.launch(cameraIntent);
}
you also have to do this as answered here:
https://stackoverflow.com/a/45751453/16645882
I can't take a picture from the camera and then store it as a Bitmap object. I can only find solutions where I get thumbnail as Bitmap. How can I do this?
Here is the code:
public boolean pickImageFromCamera(View View) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo;
try
{
// place where to store camera taken picture
photo = this.createTemporaryFile("picture", ".jpg");
photo.delete();
}
catch(Exception e)
{
System.out.println("ERROR TAKING PICTURE");
return false;
}
mImageUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageUri);
//start camera intent
activity.startActivityForResult(intent, REQUEST_CODE2);
return true;
}
private File createTemporaryFile(String part, String ext) throws Exception
{
File tempDir= Environment.getExternalStorageDirectory();
tempDir=new File(tempDir.getAbsolutePath()+"/.temp/");
if(!tempDir.exists())
{
tempDir.mkdirs();
}
return File.createTempFile(part, ext, tempDir);
}
public void pickImageFromFolder(View View) {
Intent pickPhoto = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto , REQUEST_CODE);//one can be replaced with any action code
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE2 && resultCode == Activity.RESULT_OK)
try {
// We need to recyle unused bitmaps
if (bitmap != null) {
bitmap.recycle();
}
Bitmap bitmap = null;
this.getContentResolver().notifyChange(mImageUri, null);
ContentResolver cr = this.getContentResolver();
try
{
bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, mImageUri);
imageView.setImageBitmap(bitmap);
}
catch (Exception e)
{
System.out.println("Failed to load");
}
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
this.UPLOAD_URL = Config.webSiteUrl + "?action=uploadFile&username=" + this.username + "&password=" + this.password + "&baustelleid=" + Fotos.this.baustelleid;
if(bitmap != null) {
uploadImage(bitmap, this.UPLOAD_URL);
}
} catch (Exception e) {
System.out.println("Fehler 1");
}
super.onActivityResult(requestCode, resultCode, data);
}
It ends up with System.out.println("ERROR TAKING PICTURE"); It seems like there is no permission to write the storage. How can I change this?
Call this method in button etc. after that get bitmap onActivityResult
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();
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"com.example.yourfileprovider",
photoFile);
photoThumbnailURI = FileProvider.getUriForFile(this,
"com.example.yourfileprovider",
photoThumbnailFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
}
This method will Create file
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;
}
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);
mImageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You will get a bitmap, but you can get the whole one, not just the thumbnail.
Have you tried this answer ? https://stackoverflow.com/a/6449092/4127441
I have a fragment that takes a canvas drawing and saves it to external memory. I go into the device by connecting the USB and searching the file directory. I find it under Android/data/appname/files/img/nameofimage.png. Now I have a 2nd fragment that is saving pictures when the camera takes them but I can't find them.
Camera
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check that request code matches ours:
if (requestCode == CALL_BACK) {
// Check if your application folder exists in the external storage,
// if not create it:
File imageStorageFolder = new File(
Environment.getExternalStorageDirectory() + File.separator
+ "Camera");
if (!imageStorageFolder.exists()) {
imageStorageFolder.mkdirs();
Log.d("FILE",
"Folder created at: " + imageStorageFolder.toString());
}
// Check if data in not null and extract the Bitmap:
if (data != null) {
String filename = "image";
String fileNameExtension = ".jpg";
File sdCard = Environment.getExternalStorageDirectory();
String imageStorageFolderName = File.separator + "Camera"
+ File.separator;
File destinationFile = new File(sdCard, imageStorageFolderName
+ filename + fileNameExtension);
Log.d("FILE", "the destination for image file is: "
+ destinationFile);
if (data.getExtras() != null) {
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
try {
FileOutputStream out = new FileOutputStream(
destinationFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
Log.e("FILE", "ERROR:" + e.toString());
}
}
}
}
}
Canvas
capSig.setView(sign = new Sign(this.getActivity(), null))
.setMessage(R.string.store_question)
.setPositiveButton(R.string.save,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
sign.setDrawingCacheEnabled(true);
sign.getDrawingCache()
.compress(
Bitmap.CompressFormat.PNG,
10,
new FileOutputStream(
new File(
getActivity()
.getExternalFilesDir(
"img"),
"signature.png")));
} catch (Exception e) {
Log.e("Error ", e.toString());
}
onClick
private class ClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, CALL_BACK);
}
}
I don't fully understand the code, why is this saving to a different location. Also what would I need to do to get it to save under Android/data/appname/files/Camera/ ?
edit
the logcat tells me its being saved here: 06-08 16:21:49.333: D/FILE(4818): the destination for image file is: /storage/emulated/0/Camera/image.jpg Which I assume is listed as private in the files and that's why I cant find it. This does not tell me why its being saved here though.
2nd Edit
Current Code
private class ClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File sdCard = Environment.getExternalStorageDirectory();
String path = sdCard.getAbsolutePath() + "/Camera" ;
File dir = new File(path);
if (!dir.exists()) {
if (dir.mkdirs()) {
}
}
String FileName = "image";
File file = new File(path, FileName + ".jpg");
Uri outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CALL_BACK);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check that request code matches ours:
if (requestCode == CALL_BACK) {
Log.v("RESULT", "Picture Taken");
}
}
Try this code
private void TakePhoto() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File sdCard = Environment.getExternalStorageDirectory();
String path = sdCard.getAbsolutePath() + "/Camera" ;
File dir = new File(path);
if (!dir.exists()) {
if (dir.mkdirs()) {
}
}
String FileName = "image";
File file = new File(path, FileName + ".jpg");
Uri outputFileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, TAKE_PICTURE);
}
Remember
You need this Permission in your Manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I need to record a video within the application using the intent. I think the code is correct, however when I do start the image stops and the file gets 0Bytes. I let down the code I'm using.
The first function called:
protected void makeVideo() {
//create new Intent
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO); // create a file to save the video
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high
// start the Video Capture Intent
startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
}
getOutputMediaFile function:
private static File getOutputMediaFile(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
// Environment.getExternalStorageState();
// File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), Constants.ALBUM.AlbumInPhone);
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), Constants.ALBUM.AlbumInPhone);
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
Log.d(Constants.ALBUM.AlbumInPhone, "failed to create directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_"+ timeStamp + ".jpg");
} else if(type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_"+ timeStamp + ".mp4");
} else {
return null;
}
File x = mediaFile;
int y=0;
y=1;
return mediaFile;
}
private static Uri getOutputMediaFileUri(int type){
return Uri.fromFile(getOutputMediaFile(type));
}
and:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
// Video captured and saved to fileUri specified in the Intent
// Toast.makeText(this, "Video saved to:\n" + data.getData(), Toast.LENGTH_LONG).show();
String uri = fileUri.getPath();
if(TextUtils.isEmpty(uri)){
Log.v(TAG, "Could not get video");
} else {
Log.v(TAG, "video: " + uri);
if(BebeDataBaseManager.addVideoToAlbum(this, uri, albumId)){
Log.v(TAG, "video: added");
this.cursor.requery();
} else {
Log.v(TAG, "video: not added");
}
}
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the video capture
} else {
// Video capture failed, advise user
}
}
...
I'm doing something wrong?