I'm fairly new to android development and I'm trying to create an app that calls implicit intent for the camera by clicking one button. Once the image is captured you can click back button to get to main activity. In the main activity there's second button that when you click it you can see recent files and the captured image should be showing there
I was working through https://developer.android.com/training/camera/photobasics.html#TaskScalePhoto
Used the following code for capturing the image
final TextView textviewcamera = (TextView) findViewById(R.id.TextView1);
final int REQUEST_IMAGE_CAPTURE = 1;
// Set an OnClickListener on this Text View
// Called each time the user clicks the Text View
textviewcamera.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
/*
opens the camera app and we are able to take a photo, photo is not save anywhere, needs to be fixed
code is from android studio, DON'T FORGET to cite
https://developer.android.com/training/camera/photobasics.html
*/
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//if (takePictureIntent.resolveActivity(getPackageManager()) != null)
//{
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
//}
}
Then I have another piece of code that shows the recent files
final TextView textviewpicture = (TextView) findViewById(R.id.TextView2);
// Set an OnClickListener on this Text View
// Called each time the user clicks the Text View
textviewpicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
opens the camera app and we are able to take a photo, photo is not save anywhere, needs to be fixed
code is from android studio, DON'T FORGET to cite
https://developer.android.com/training/camera/photobasics.html
*/
Intent viewpicture = new Intent();
viewpicture.setType("image/*");
viewpicture.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(viewpicture, "Select Picture"), 10);
}
});
I'm able to open the camera and take the photo however when I try to view it in my recent files, this part is not working.
Any help would be highly appreciated
Thanks a mill everyone :)
override your onActivityresult there you can preview your image from there save it to external storage
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_IMAGE_CAPTURE:
if (resultCode != RESULT_CANCELED)
{
if (resultCode == RESULT_OK) {
BitmapFactory.Options options = new
BitmapFactory.Options();
options.inSampleSize = 8;
Bitmap bitmap = BitmapFactory.decodeFile(fileUri.getPath(),
options);
saveImageToExternalStorage(bitmap)
}
} else{
//show error message
}
} }
public static File saveImageToExternalStorage(Bitmap finalBitmap) {
File file;
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
File myDir = new File(root + "/easyGovs");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".png";
file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.PNG, 55, out);
out.flush();
out.close();
return file;
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
and while passing your intent for camera use this -
private Uri fileUri;
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
// start the image capture Intent
startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
Related
I've a layout to portrait and a layout to landscape. In those layout, there is a ImageView with onClick listener. My ImageView has a default image (a camera icon)
When I push into ImageView, open a dialog and I can open camera and take a picture or open gallery and select a image.
Then, I save a bitmap and put it in the ImageView. This bitmap is a global variable in my class.
But when I turn my app, load my other layout (main_landscape) and if I took a pic, I lose my bitmap and charge default image.
This is my code:
public void takePicture(View view) {
final CharSequence[] options = { "Take a pic", "Gallery","Cancel" };
//Build an AlertDialog object
AlertDialog.Builder builder = new AlertDialog.Builder(Main.this);
builder.setTitle("Picture");
//onClickListener method
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int selected) {
if(options[selected].equals("Take a pic")){
//open camera
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
//this is my global bitmap and I put it null when I push take a picture
resized=null;
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
else if(options[selected].equals("Gallery")){
Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
}
else{
dialog.dismiss();
}
//if user doesn't select anything, show default icon
//show picture is my layout ImageView and cameraicon is my default icon
showPicture.setImageResource(R.drawable.cameraicon);
}
});
builder.show();
}
This is my onActivityResult code:
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
//if my resultCode is RESULT_OK
if(resultCode == RESULT_OK){
if(requestCode==1){
File f = new File(Environment.getExternalStorageDirectory().toString());
for(File temp: f.listFiles()){
if(temp.getName().equals("temp.jpg")){
f=temp;
break;
}
}
try{
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
newHeight=600;
newWidth=900;
//resized is my global bitmap
resized = Bitmap.createScaledBitmap(bitmap, newWidth, newHeight, true);
//show my new bitmap in my ImageView
showPicture.setImageBitmap(resized);
} catch (Exception e) {
e.printStackTrace();
}
}
//I choose gallery option
else if(requestCode==2){
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage,filePath,null,null,null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
newHeight=600;
newWidth=900;
//my global bitmap
resized = Bitmap.createScaledBitmap(thumbnail, newHeight, newWidth, true);
//show new bitmap in my ImageView
showPicture.setImageBitmap(resized);
}
}
}
When I turn my phone, I loose my bitmap. What I can do, please?
Thanks a lot!!
I think you save the value of your Bitmap by calling onSaveInstaceState(Bundle bundle) and then restore it when the activity is recreated.
You might want to store the filename to your photo file inside the activity:
class MyActivity {
File imageFile = null;
}
Since your activity will get destroyed on rotation, you need to save that image file name in onSaveInstanceState():
public void onSaveInstanceState(Bundle outState)
{
if (imageFile != null) {
outState.putString("IMAGE_FILENAME", imageFile.getAbsolutePath());
}
}
Bitmaps in android are Parcelable, so instead of storing the filename of the image you could also save the Bitmap itself.
The saved state gets passed to onCreate() when your activity gets re-created:
public void onCreate(Bundle savedState)
{
super.onCreate(savedState);
if (savedState != null) {
String imagePath = saveState.getString("IMAGE_FILENAME");
if (imagePath != null) {
imageFile = new File(imagePath);
}
}
updateImageView();
}
public void updateImageView()
{
// code from onActivityResult() to load the image
}
Side Notes:
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp: f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
You are writing to the global, external storage directory. Please don't do this, use your application's files' directory. Also, no need to search for a fixed filename in the path, simply check if the file exists.
File imageFile = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES), imageFileName);
if (imageFile.exists()) {
[...]
}
I think better way to do it is using fragment instead activity.
Use method fragment.setRetainInstance(true), and fragment will not be destroyed, when you turn your device.
In my app i'm using the camera app on the phone in order to take a picture. After taking the picture it returns back to my app. I noticed that it acts differently in different phones. In Galaxy s3 I found that after taking a picture it shows the picture and gives an option to save it (and then go back to my app) or discard (and go back to the camera app). The problem is that when the screen is rotated the app crushes when the save/discard screen appears. The only way to stop it from crushing is to take the picture without rotating the screen and keep it that way.
Is there a solution to this problem? Maybe there is a way that I can define that it won't allow rotation at this screen?
Here is the code:
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//Specify target file
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
newPicName = android.os.Environment.getExternalStorageDirectory() + "/"+app.APP_FOLDER + "/" + app.getSession()+ "_"+app.getDateTime()+ "_" +sdf.format(cal.getTime()) +".jpg";
File imageFile = new File(newPicName);
Uri imageFileUri = Uri.fromFile(imageFile);
intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, imageFileUri);
startActivityForResult(intent, 0);
If you just want to limit the orientation of the screen you need to specify it in your manifest… For example:
<activity
android:name="com.xxx"
android:label="#string/xxx"
android:screenOrientation="portrait" > //this limits the screen to only portrait.
</activity>
Additional Info
This is how I do it and it works for me perfectly.
//instance variables
private static final int TAKE_PICTURE = 0;
private Uri mUri;
private Bitmap mPhoto;
//First I create a method to capture the image.
private void captureImage() {
Intent i = new Intent("android.media.action.IMAGE_CAPTURE");
File f = new File(Environment.getExternalStorageDirectory(), "profile.jpg");
i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
mUri = Uri.fromFile(f);
startActivityForResult(i, TAKE_PICTURE);
}
//Then I handle the result.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE://this is a constant defined in my instance variables.
if (resultCode == Activity.RESULT_OK) {
getContentResolver().notifyChange(mUri, null);
ContentResolver cr = getContentResolver();
try {
mPhoto = android.provider.MediaStore.Images.Media.getBitmap(cr, mUri);
//set your photo in a screen…
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}
Try following code :
private File tempFile;
private static final int CAMERA_IMAGE = 1;
public void takePicFromCamera() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (tempFile != null) {
Log.i(""image Path : "", tempFile.getPath());
Uri picUri = Uri.fromFile(tempFile); // convert path to Uri
intent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
Log.i("Picture Uri", " : " + picUri);
}
startActivityForResult(intent, MedicationConstants.CAMERA_IMAGE);
}
public void onActivityResult(int requestCode, int resultCode, final Intent intent) {
if (requestCode == MedicationConstants.CAMERA_IMAGE) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (tempFile != null) {
//do anything with image file. Store in database. Or even should add functionality of dropping
}
}
}, 2000);
}
}
In on onActivityResult you should add functionality of image cropping. Please have a look at simple-crop-image-lib. It is great library & works for almost all device.
Thanks
I have an Android app with an ImageButton. When user clicks on it, intent launches to show camera activity. When user capture the image, I'd like to save it in drawable folder of the app and display it in the same ImageButton clicked by the user, replacing the previous drawable image. I used the activity posted here: Capture Image from Camera and Display in Activity
...but when I capture an image, activity doesn't return to activity which contains ImageButton.
Edit code is:
public void manage_shop()
{
static final int CAMERA_REQUEST = 1888;
[...]
ImageView photo = (ImageView)findViewById(R.id.getimg);
photo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent camera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, CAMERA_REQUEST);
}
});
[...]
}
And onActivityResult():
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
ImageButton getimage = (ImageButton)findViewById(R.id.getimg);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK)
{
Bitmap getphoto = (Bitmap) data.getExtras().get("data");
getimage.setImageBitmap(getphoto);
}
}
How can I also store the captured image in drawable folder?
once you've saved the image to a file you can use the following snippet to add to gallery.
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, new File(path).toString());
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATA, path);
getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI , values);
to save the file to a directory do the following
private saveFileToDir() {
final InputStream in = Wherever you input stream comes from;
File f = generatePhotoFile();
OutputStream out = new FileOutputStream(f);
byte[] buffer = new byte[1024];
int len;
while ((len=in.read(buffer))>0)
{
out.write(buffer,0,len);
}
in.close();
out.flush();
out.close();
}
private File generatePhotoFile() throws IOException {
Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyymmdd_hhmmss");
String newPicFile = "IMG_"+ df.format(date) + ".jpg";
File f = new File(Environment.getExternalStorageDirectory()+"/DCIM/Camera/", newPicFile);
if (!f.exists())
{
if(!f.getParentFile().exists())
f.getParentFile().mkdir();
f.createNewFile();
}
return f;
}
How can I also store the captured image in drawable folder?
It's not possible to save an image to the drawable folder dynamically:
See:
android image save to res/drawable folder
and
Write to /res/drawable/ on the fly?
I want to capture image & save it to SD card. Now its working fine.
My problem is 1) after capture OK and Cancel button are avialble.When I click Ok only it need to save the image into SD card.
2) It doesn't come to onActivityResult method. I have written my onActivityResult inside the ActivityGroup class.
This code for When User click on Camera button, it will open cameara & save it
//Camera
Button btnCamera =(Button)findViewById(R.id.btnCamera);
btnCamera.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
selectedImagePath = Environment.getExternalStorageDirectory()+"/"+retailerCode+"-"+count+".jpg";
imgName =retailerCode+"-"+count+".jpg";
count++;
File file = new File(selectedImagePath);
Uri outputFileUri = Uri.fromFile(file);
Intent intent = new Intent (android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
Bundle b = new Bundle();
b.putString("Activity", "RetailerOrderSActivity");
b.putString("RetailerName", seletctedRetailer);
b.putString("RetailerCode", retailerCode);
intent.putExtras(b);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
onPhotoTaken();
}
});
protected void onPhotoTaken() {
_taken = true;
DBAdapter dbAdapter = DBAdapter.getDBAdapterInstance(CameraMainActivity.this);
dbAdapter.openDataBase();
boolean status = dbAdapter.saveImageInfo(retailerCode,strExecutive,strBusinessUnit,strTerritoryCode,imgName,visitNumber);
if(status) {
Toast.makeText(SalesActivityGroup.group.getApplicationContext(), "Image has been saved successfully" , Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(SalesActivityGroup.group.getApplicationContext(), "Image has not been saved successfully" , Toast.LENGTH_SHORT).show();
}
dbAdapter.close();
lstCaptures = getAllImage(imgDateVal.getText().toString());
imageViewTable.removeAllViews();
loadTableLayout();
}
This is code for ActivityGroup
public class SalesActivityGroup extends ActivityGroup {
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
System.out.println("===REQUEST=====" +requestCode);
System.out.println("==resultCode==" +resultCode); } }
Actually I need to call onPhotoTaken from onActivityResult. According current my code if the user click cancel also, it saving information to DB. Image is not captured..
This is my app image :
This is button showing after capture image:
Please anybody sort out this issue..
Thanks in advance
Check the following answer
Suppose I have a button Select & when the user clicks on the button , Camera screen will open.
btn_select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String fileName = new StringBuilder(String.valueOf(System.currentTimeMillis())).append(
".jpg").toString();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mCapturedImageURI = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
startActivityForResult(intent, IShipdocsMobileConstants.CAMERA_ACTION);
}
});
After the user takes a photo & clicks on the Save/OK button (depends on the mobile device) , use the following code to fetch the data for the captured image.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == IShipdocsMobileConstants.CAMERA_ACTION) {
if (resultCode == RESULT_OK) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(mCapturedImageURI, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor.getString(column_index_data);
SelectedFileInfo selectedFileObj = null;
ArrayList<SelectedFileInfo> cameraArrList = new ArrayList<SelectedFileInfo>();
File fileObj = new File(capturedImageFilePath);
String fileSize = String.valueOf(fileObj.length()); //File Size
String fileName = Utils.getFileName(capturedImageFilePath); //File Name
}else if (resultCode == RESULT_CANCELED) {
// handle the condition in which the user didn't save the image
}
} else {
// handle the condition in which the request code was not CAMERA_ACTION , maybe send the user to the home/default screen
}
}
}
Problem is calling place I need to call getParent().startActivityForResult(intent, CAMERA_PIC_REQUEST); more details see here
I am using the following code to take picture, using the device camera. I am new to android. Can anybody please help me and tell me where I should specify the path. I want to save images in a separate folder in sd card. Any help is deeply appreciated.
private static final int CAMERA_PIC_REQUEST = 2500;
bcontinue.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_PIC_REQUEST && resultCode==RESULT_OK)
{
try{
Byte image1 = (Byte) data.getExtras().get("data");
FileOutputStream fos = openFileOutput("filename.bmp", Context.MODE_PRIVATE);
fos.write(image1);
fos.close();
}
catch(Exception e){
}
Bitmap image = (Bitmap) data.getExtras().get("data");
ImageView imageview = (ImageView) findViewById(R.id.imageView1);
imageview.setImageBitmap(image);
Context context = getApplicationContext();
CharSequence text = "Click on the image!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
The below code will start the default camera and have the camera save the image to the specified uri. The key is to put the extra "MediaStore.EXTRA_OUTPUT" along with the desired uri.
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/Images/" + image_name + ".jpg");
Uri imageUri = Uri.fromFile(file);
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, 0);