I am a beginner in android programming.
Here is a code to take a image and save it in a folder in sdcard. The image is saved in gallery but it is not saved in the location where i want to. Please help...
public class CameraActivity extends Activity {
/** Called when the activity is first created. */
Button button1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button1=(Button)findViewById(R.id.button1);
}
public void send(View v)
{
Intent imageIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(
Environment.getExternalStorageDirectory(),
"MyImages");
imagesFolder.mkdirs(); //
File image = new File(imagesFolder, "image_001.jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent,0);
}
}
Finally I got the solution, the modified code is:
File image = new File("/sdcard/picture.jpg");
Uri uriSavedImage = Uri.fromFile(image);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
// start the image capture Intent
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
You should append a / to your MyImages string. eg,
new File(Environment.getExternalStorageDirectory() + "/MyImages/");
That should create a reference to a directory, not a file as it currently is.
Related
In my app the user can take an image from the camera and use as a profile picture. Everything works, except that when the user leaves the app and returns then the image isn't there anymore. So how can I save that image to stay there even when the user exits the app?
Code for camera intent:
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
And onActivityResult:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
getLayoutInflater().inflate(R.layout.custon_header,null);
ImageView profimg = (ImageView) findViewById(R.id.roundedimg);
profimg.setImageBitmap(photo);
Could someone please assist me with this?
Thanks
data.getExtras().get("data");
only returns the thumbnail of the image which would be on low quality. You have to specify on your camera intent a location where the image will be saved:
File outputFile = new File(Environment.getExternalStorageDirectory() +"/myOutput.jpg");
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(Intent.EXTRA_OUTPUT,outputFile.getAbsolutePath());
startActivityForResult(cameraIntent, CAMERA_REQUEST);
and on your activityResult, simply use the outputfile for your bitmap:
bitmap = BitmapFactory.decodeFile(outputFile.getAbsolutePath());
You can configure the intent to store the image, using EXTRA_OUTPUT like this:
Intent imageIntent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
File imageFolder = new File(Environment
.getExternalStorageDirectory(), "YourFolderName");
if (!imagesFolder.exists()) {
imagesFolder.mkdirs();
}
File imageFile = new File(imagesFolder, "user.jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
imageIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION,
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
activity.startActivityForResult(imageIntent, CAMERA_REQUEST);
So you have the path and can decode the file to bitmap.
You need to save that image in sd-card or phone memory so that it can be accessed when you open your app again. You are seeing that image as soon as you take the image because it is there in the memory and as soon as you leave the app, the memory is released.
private void SaveBitmapInDirectory(Bitmap bitmap, String fileName)
{
File direct = new File(Environment.getExternalStorageDirectory() + "/dirName");
if (!direct.exists())
{
File profilePic = new File("/sdcard/dirName/");
profilePic.mkdirs();
}
File file = new File(new File("/sdcard/dirName/"), fileName);
if (file.exists())
{
file.delete();
}
try
{
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
And load the file from directory in onCreate function by calling the following function:
void loadProfilerImage(String fileName)
{
File file = new File(new File("/sdcard/dirName/"), fileName);
if (file.exists())
{
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
ImageView.setImageBitmap(myBitmap);
}
}
Hi Guys My application quits just after the image is saved, I cannot see why, Please help?
This is the button pressed method, after the picture is taken I press save, The image gets saved where it needs to be saved but the application just quits after I press save, It does not say "Not Responding", it just quits
cam.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
leakerID = leakId.getText().toString();
String direc = "/e3softData/DCIM/";
String fileName = leakerID+".jpg";
// get the path to sdcard
File sdcard = Environment.getExternalStorageDirectory();
// to this path add a new directory path
File dir = new File(sdcard.getAbsolutePath() + direc);
// create this directory if not already created
dir.mkdir();
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File file = new File(dir, fileName);
String f = file.toString();
Uri uriSavedImage = Uri.fromFile(new File(f));
intent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(intent, 0);
}
});
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir = new File(Environment.getExternalStorageDirectory() + "/e3softData/DCIM/");
if (!dir.exists()) {
dir.mkdir();
}
String fileName = leakerID+".jpg";
output = new File(dir.getAbsolutePath(), fileName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(intent, 0);
}
I am able to use my camera and take pictures by below:
public class ImportCard extends Activity {
ImageButton importimage;
Button btnglry, btnqr;
boolean taken;
String path;
protected static final String PHOTO_TAKEN = "photo_taken";
static Uri capturedImageUri=null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_import_card);
path = Environment.getExternalStorageDirectory() + "/MapCards/"+System.currentTimeMillis()+".jpg";
String dir = Environment.getExternalStorageDirectory().getPath();
File imageDirectory = new File(dir);
imageDirectory.mkdirs();
importimage = (ImageButton)findViewById(R.id.importimage);
importimage.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
startCameraActivity();
}
});
}
protected void startCameraActivity()
{
File file = new File( path );
Uri outputFileUri = Uri.fromFile( file );
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
startActivityForResult(intent, 0);
}
protected void onPhotoTaken()
{
// Log.i( "MakeMachine", "onPhotoTaken" );
taken = true;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 4;
}}
This method works. But i want my captured images to save in a default target folder such as "MapCards" (if no folder, then create). It is something to do with,
path = Environment.getExternalStorageDirectory() + "/MapCards/"+System.currentTimeMillis()+".jpg";
But all images are saved in "Camera" folder. Thank you for your helps.
Create your own folder in SD card & then pass the File Uri as extra with camera intent. This code should do the trick.
String SD_CARD_TEMP_DIR = Environment.getExternalStorageDirectory() + File.separator + "tempImage.jpg";
File file =new File(SD_CARD_TEMP_DIR);
takePictureFromCameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
Refer to Android's training-Taking Photos Simply.
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE );
intent.putExtra( MediaStore.EXTRA_OUTPUT, outputFileUri );
is the only way to save image to custom file path. so what you should do:
1. check whether you have the correct saving folder
2. try to remove your sdcard to verify whether your code can work
3. Is your ROM customized? the 3rd-party ROM may not work well.
I just want to save a picture in my Imagefolder in my phone.
I have got 2 examples which I tried.
1. Example
My app crashes when I activate the onClick Method:
public void onClick(View arg0) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1337);
}});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if( requestCode == 1337)
{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
}
else
{
Toast.makeText(AndroidCamera.this, "Picture NOt taken", Toast.LENGTH_LONG);
}
super.onActivityResult(requestCode, resultCode, data);
}
2. Example
Before I saved my taken Picture with Uri. But it saved my picture in a folder, which I can only access on my PC or with a FileApp. I donĀ“t know how I can change the Path direction with Uri to my existing default image folder in my phone.
Uri uriTarget = getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, new ContentValues());
This is how I manage with saving images to specified imagefolder
When starting camera intent I define path and directory, where my image should be saved, and pass this as intetn extra when starting camera:
private void startCameraIntent() {
//create file path
final String photoStorePath = getProductPhotoDirectory().getAbsolutePath();
//create file uri
final Uri fileUri = getPhotoFileUri(photoStorePath);
//create camera intent
final Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//put file ure to intetn - this will tell camera where to save file with image
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start activity
startActivityForResult(cameraIntent, REQUEST_CODE_PHOTO_FROM_CAMERA);
//start image scanne to add photo to gallery
addProductPhotoToGallery(fileUri);
}
And here are some of helper methods used in code above
private File getProductPhotoDirectory() {
//get directory where file should be stored
return new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES),
"myPhotoDir");
}
private Uri getPhotoFileUri(final String photoStorePath) {
//timestamp used in file name
final String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.US).format(new Date());
// file uri with timestamp
final Uri fileUri = Uri.fromFile(new java.io.File(photoStorePath
+ java.io.File.separator + "IMG_" + timestamp + ".jpg"));
return fileUri;
}
private void addProductPhotoToGallery(Uri photoUri) {
//create media scanner intetnt
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
//set uri to scan
mediaScanIntent.setData(photoUri);
//start media scanner to discover new photo and display it in gallery
this.sendBroadcast(mediaScanIntent);
}
Theres a problem I can't seem to fix:
In my OnCreate in the CameraActivity, I delete the picture first if it's there. If there is a situation where this is done, the picture file is created but the picture is blank. (so only creates the picture successfully if the file isn't there in the first place). How do I delete the file and create it successfully?
My CameraActivity is defined as follows:
public class CameraActivity extends Activity
{
final int PICTURE_ACTIVITY = 1;
#Override
public void onCreate(Bundle savedInstanceState)
{
Intent h = getIntent();
String filename = h.getStringExtra("string") + ".jpg";
String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + getString(R.string.app_name)+ "/";
File newdir = new File(dir);
try{
newdir.mkdirs();
}
catch(Exception e){}
String file = dir + filename;
File newfile = new File(file);
boolean deleted = newfile.delete();
try {
System.out.println("creating:");
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
super.onCreate(savedInstanceState);
startActivityForResult(cameraIntent, PICTURE_ACTIVITY);
}
}
I realised the reason it wasn't saving sometimes was because I was taking the SD card out of the phone before it had the chance to save.