I am developing an app that can take pictures using intents and save it to storage. After taking 10 to 15 pictures the app is gets very slow. Code for taking picture is as follows:
private void capturePhoto() {
File root = new File(Environment.getExternalStorageDirectory(), "Feedback");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, Constants.PROFILE_IMAGE_NAME + ".jpeg");
Uri outputFileUri = Uri.fromFile(file);
Intent photoPickerIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
photoPickerIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
photoPickerIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
photoPickerIntent.putExtra("return-data", true);
photoPickerIntent.putExtra("android.intent.extras.CAMERA_FACING", 1);
startActivityForResult(photoPickerIntent, requestCode);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (this.requestCode == requestCode && resultCode == RESULT_OK) {
File file = new File(root, Constants.PROFILE_IMAGE_NAME+".jpeg");
checkFlowIdisPresent(file);
displayPic();
}
}
private void displayPic() {
String filePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + File.separator + "/Feedback/" + Constants.PROFILE_IMAGE_NAME + ".jpeg";
// Bitmap bmp = BitmapFactory.decodeFile(filePath);
//Bitmap scaled = Bitmap.createScaledBitmap(bmp, 300, 300, true);
File imgFile = new File(filePath);
Bitmap bmp = decodeFile(imgFile);
if (imgFile.exists()) {
dispProfilePic.setImageBitmap(bmp);
} else {
dispProfilePic.setBackgroundResource(R.drawable.user_image);
}
}
Edited DisplayPic() method is shown above
You need to use a image loading library to load the images.
Glide is my fav one.
its setup is very simple:
put this n your build.gradle
dependencies {
compile 'com.github.bumptech.glide:glide:3.7.0'
}
Then your method will be
private void displayPic() {
String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "/Feedback/" + Constants.PROFILE_IMAGE_NAME + ".jpeg";
Glide.with(context).load(filePath).override(300, 300).into(dispProfilePic);
}
You can find more informatin and usage details here.
Related
So the app I have, takes a photograph (or uses from library) and brings the captured photo into an editing view. The code for the camera capture is;
public void cameraClicked(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 2);
}
The camera view opens, allows me to take a photo, but when it moves to EditorActivity.class the photo is not there, just a black screen. The editor view is fine, but it does not seem to be taking what I capture with the camera. I have set the correct permissions, this works fine in versions prior to Level 23
SDK version.
Edit - updated code methods below;
boolean SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".jpg";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
// Tell the media scanner about the new file so that it is
// immediately available to the user.
MediaScannerConnection.scanFile(this, new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("ExternalStorage", "Scanned " + path + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});
return false;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case 2:
if (resultCode == RESULT_OK) {
Log.e("TAG", "work here");
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
SaveImage(thumbnail);
Intent intent = new Intent(this, EditorActivity.class);
startActivity(intent);
}
break;
}
}
I'm a newbie android developer.Now I found an error when I compiled my camera application.
Actually the camera intent is working properly and the image taken can be shown on ImageView, but it isn't saved automatically to my phone gallery. After research, it took 3 days after picture taken to get saved in the image gallery.
I already tried some different methods of camera intent, but until now I have no significant results. Any help will be so much appreciated, thank you.
my target SDK is 27 API, I already made an XML file for provider_paths and describe it in my manifests.
here is my camera intent:
public static final int REQUEST_CAMERA = 100;
Uri fileUri;
public final int SELECT_FILE = 11;
int bitmap_size = 40; // image quality 1 - 100;
int max_resolution_image = 800;
private void openCamera() {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, REQUEST_CAMERA);
}
public Uri getOutputMediaFileUri() {
return FileProvider.getUriForFile(LaporActivity.this,
BuildConfig.APPLICATION_ID + ".fileprovider",
getOutputMediaFile());
}
private static File getOutputMediaFile() {
// External sdcard location
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "KSD");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e("Monitoring", "Oops! Failed create Monitoring directory");
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_KSD_" + timeStamp + ".jpg");
return mediaFile;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.e("onActivityResult", "requestCode " + requestCode + ", resultCode " + resultCode);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA) {
try {
Log.e("CAMERA", fileUri.getPath());
bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(fileUri));
setToImageView(getResizedBitmap(bitmap, max_resolution_image));
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == SELECT_FILE && data != null && data.getData() != null) {
try {
// choose picture from Gallery
bitmap = MediaStore.Images.Media.getBitmap(LaporActivity.this.getContentResolver(), data.getData());
setToImageView(getResizedBitmap(bitmap, max_resolution_image));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void setToImageView(Bitmap bmp) {
//compress image
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, bitmap_size, bytes);
decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(bytes.toByteArray()));
//shows chosen picture from gallery to imageview
fotoCaptured.setImageBitmap(decoded);
}
public Bitmap getResizedBitmap(Bitmap image, int maxSize) {
int width = image.getWidth();
int height = image.getHeight();
float bitmapRatio = (float) width / (float) height;
if (bitmapRatio > 1) {
width = maxSize;
height = (int) (width / bitmapRatio);
} else {
height = maxSize;
width = (int) (height * bitmapRatio);
}
return Bitmap.createScaledBitmap(image, width, height, true);
}
I expected the picture to get saved automatically to my gallery so I can continue to upload-process method using Retrofit, but the actual is when I clicked upload-button, the toast shows "IMGxxxxx No such file/directory" because the image path is not properly saved.
Your file exist in memory but not on disk. Create the file before returning the object
private static File getOutputMediaFile() {
...
...
//create file on disk
if(!mediaFile.exists()) mediaFile.createNewFile();
return mediaFile;
}
I am capturing an image and store it in storage in mobile but when I get this image it cannot show any thing in Image View. I have tried a lot of code to get images from file but none of them are working in my emulator or real Samsung device.
enter code here
imageHolder = (ImageView)findViewById(R.id.captured_photo);
Button capturedImageButton = (Button)findViewById(R.id.photo_button);
capturedImageButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(photoCaptureIntent, requestCode);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(this.requestCode == requestCode && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
String partFilename = currentDateFormat();
storeCameraPhotoInSDCard(bitmap, partFilename);
// display the image from SD Card to ImageView Control
String storeFilename = "photo_" + partFilename + ".jpg";
Bitmap mBitmap = getImageFileFromSDCard(storeFilename);
imageHolder.setImageBitmap(mBitmap);
}
}
private String currentDateFormat(){
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
String currentTimeStamp = dateFormat.format(new Date());
return currentTimeStamp;
}
private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate){
File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Bitmap getImageFileFromSDCard(String filename){
/* Bitmap bitmap = null;
File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
try {
FileInputStream fis = new FileInputStream(imageFile);
bitmap = BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return bitmap; */
File imageFile = new File(Environment.getExternalStorageDirectory() + filename);
// File imgFile = new File(filename);
//("/sdcard/Images/test_image.jpg");
Bitmap myBitmap;
if(imageFile.exists()){
myBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
// ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
// myImage.setImageBitmap(myBitmap);
return myBitmap;
}
return null;
}
First of All make sure you have declared the "Access External Storage" and "Access Hardware Camera" permissions in "AndroidManifest" and if you are using Android version 23 or 23+ then you have to take permissions on run-time.
If this is not the problem then use this code given below, it's working fine for me.
For Camera:
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePicture, ACTION_REQUEST_CAMERA);
For Gallery:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
Intent chooser = Intent.createChooser(intent, "Choose a Picture");
startActivityForResult(chooser, ACTION_REQUEST_GALLERY);
OnActivityResultMethod:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ACTION_REQUEST_GALLERY:
Uri galleryImageUri = data.getData();
try{
Log.e("Image Path Gallery" , getPath(getActivity() , galleryImageUri));
selectedImagePath = getPath(getActivity() , galleryImageUri);
} catch (Exception ex){
ex.printStackTrace();
Log.e("Image Path Gallery" , galleryImageUri.getPath());
selectedImagePath = galleryImageUri.getPath();
}
break;
case ACTION_REQUEST_CAMERA:
// Uri cameraImageUri = initialURI;
Uri cameraImageUri = data.getData();
Log.e("Image Path Camera" , getPath(cameraImageUri));
selectedImagePath = getPath(cameraImageUri);
break;
}
}
}
Method to get path of Image returned from Camera:
/**
* helper to retrieve the path of an image URI
*/
public String getPath(Uri uri) {
// just some safety built in
if( uri == null ) {
// TODO perform some logging or show user feedback
return null;
}
// try to retrieve the image from the media store first
// this will only work for images selected from gallery
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
// this is our fallback here
return uri.getPath();
}
I'm trying to store a newly captured image through the Camera on my Storage and then display the image on an imageview. However, the image does not get stored.
My code:
private SurfaceView mSurfaceView;
private SurfaceHolder mSurfaceHolder;
private Camera mCamera;
......more code...
captureImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mCamera.takePicture(null, null, new PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile;
pictureFile = new File(String.format("/sdcard/%d.jpg", System.currentTimeMillis()));
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
}
catch (Exception e) {
Log.d("ERR",e.toString());
}
//Display
Uri uri = Uri.fromFile(pictureFile);
imageViewer.setImageURI(uri);
}
});
}
});
Is my code correct for writing and displaying the image? I do not see any image on my storage and the imageview doesn't get populated by the image either. What am I doing wrong?
Create folder where you want to keep your photos.
Give full path name to create file .
//in this example MyImages is folder where you will keep your photos
File storageDir = new File(Environment.getExternalStorageDirectory() + "/", "MyImages");
if (!storageDir.exists()) {
storageDir.mkdirs();//directory created
}
// get the current timestamp
String timest = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
//Create your picture file
File pictureFile;
pictureFile = new File(storageDir.getPath()+File.separator+ "IMG_" + timeStamp + ".jpg");
1- make sure you have what it takes Permissions
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
2- Create a directory on your mobile
public static void createDirectory(Context context) {
String directoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/YOURDIRECTORYNAME";
try {
File directory = new File(directoryPath);
if (!directory.exists()) {
directory.mkdirs();
}
} catch (Exception e) {
e.printStackTrace();
}
}
3- This method used to take the photo and create file.
private void takePictures() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
}
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
}
4- Creates the file and save it in the folder.
private File createImageFile() throws IOException {
Calendar c = Calendar.getInstance();
SimpleDateFormat timeData = new SimpleDateFormat("dd-MMM-yyyy-HH:mm:ss");
//TODO declared global variables datePicture and imageFileName
datePicture = timeData.format(c.getTime());
imageFileName = Config.IMAGE_NAME_DEFOULT + datePicture;
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES + "/YOURDIRECTORYNAME");
File image = File.createTempFile(imageFileName, ".png", storageDir);
Log.v("test_photo" ,image.getName());
//TODO declared global variables fileName and mCurrentPhotoPath
fileName = image.getName();
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
5- Get the picture reveal it in your imageView and save in your DB.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if (resultCode == getActivity().RESULT_OK) {
//show directly
Bundle extras = data.getExtras();
Bitmap bitmap = extras.get("data");
youtImageView.setImageBitmap(bitmap);
/* here show in your imageView directly or
insert into database variables fileName and mCurrentPhotoPath
then you'll have to get it if you want to display from the DB */
} else if (resultCode == getActivity().RESULT_CANCELED) {
}
}
}
I hope it helps!
First, does your app's manifest contain the necessary permission to write to the SD card?
<manifest ...>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
...
</manifest>
and second, I'm not sure that you have the correct path to the SD card. The API docs suggest:
File sdPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String filename = Long.toString(System.currentTimeMillis())+".jpg";
File pictureFile;
pictureFile = new File(sdPath, filename);
EDIT: To display the image using the URL, you could try:
FileInputStream inputStream = new FileInputStream(pictureFile);
Drawable d = Drawable.createFromStream(inputStream, pictureFile.getName());
imageViewer.setImageDrawable(d);
I can load the picture to the background then I have also been able to "sketchify" it but when I try to save it so that I can email it as an attachment I can only figure out haw to grab the original image and what I have here makes the activity close
public void startCamera(View v) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
seek.setVisibility(View.GONE);
if (takePicture.resolveActivity(getPackageManager()) != null) {
picSpot = new File(Environment.getExternalStorageDirectory(),
"sketch.png");
outputFileUri = Uri.fromFile(picSpot);
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(takePicture, REQUEST_IMAGE_CAPTURE);
}
}
public void sendPic(View v) {
Intent sharePic = new Intent(Intent.ACTION_SEND);
if (didsketch == false) {
sharePic.setType("image/png");
sharePic.putExtra(Intent.EXTRA_STREAM, outputFileUri);
sharePic.putExtra(Intent.EXTRA_SUBJECT, "Check This Out!");
sharePic.putExtra(Intent.EXTRA_TEXT,
"I did this on my Sketchify App!");
startActivity(Intent.createChooser(sharePic, "Send Email"));
} else {
try {
FileOutputStream out = new FileOutputStream(finalSpot);
back.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
outputFileUri = Uri.fromFile(finalSpot);
sharePic.setType("image/png");
sharePic.putExtra(Intent.EXTRA_STREAM, outputFileUri);
sharePic.putExtra(Intent.EXTRA_SUBJECT, "Check This Out!");
sharePic.putExtra(Intent.EXTRA_TEXT,
"I did this on my Sketchify App!");
startActivity(Intent.createChooser(sharePic, "Send Email"));
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
sketchit.setEnabled(true);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
DisplayMetrics metrics = this.getResources().getDisplayMetrics();
screenHeight = metrics.heightPixels;
screenWidth = metrics.widthPixels;
location = Environment.getExternalStorageDirectory()
+ "/sketch.png";
back = Camera_Helpers.processImage(location, screenHeight,
screenWidth);
taken = true;
sketchit.setEnabled(taken);
shareit.setEnabled(taken);
image.setImageBitmap(back);
}
}
back is the modified bitmap i am trying to eventually attach to the email
Thanks!!!
Create Folder Directory and Save image into it: create directory where you want to save your images. Suppose the folder name is ImageFolder.
String location = Environment.getExternalStorageDirectory() + "/ImageFolder/";
//Creating Folder Directory
File imageDir = new File(location);
dir.mkdirs();
//Creating Image file
String imageName = "sketch.png";
File imageFile = new File(imageDir, imageName);
//If image file already exists then delete it.
if (imageFile.exists()) {
imageFile.delete();
}
//Writing the image to SDCard
try {
FileOutputStream out = new FileOutputStream(imageFile);
back.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}