This question already has an answer here:
Android camera Intent not saving in gallery [duplicate]
(1 answer)
Closed 5 years ago.
I am new to programming and especially Android. I am making a simple application where I am invoking the camera and taking a picture, the picture is then displayed in an ImageView but I also want it to be stored in the gallery when I click the button to view the stored pictures.
My Code:
package com.example.picture.app;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
public class MainActivity extends AppCompatActivity {
public static final int CAMERA_REQUEST = 10;
private ImageView imgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get access to the image view
imgView = findViewById(R.id.imgView);
}
//this method will be called when the take photo button is clicked
public void btnTakePhotoClicked(View v) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
public void onImageGalleryClicked(View v) {
//invoke the image gallery using n implicit intent
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
//where do we want to find the data
File pictureDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
String pictureDirectoryPath = pictureDirectory.getPath();
//get a uri representation
Uri data = Uri.parse(pictureDirectoryPath);
//set the data and the type. Get all image types
photoPickerIntent.setDataAndType(data, "image/*");
startActivityForResult(photoPickerIntent, 20);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//DID THE USER CHOOSE OK? If so code inside this code will execute
if (resultCode == RESULT_OK) {
if (requestCode == CAMERA_REQUEST) {
//WE ARE HEARING BACK FROM THE CAMERA
Bitmap cameraImage = (Bitmap) data.getExtras().get("data");
//at this point we have the image from the camera
imgView.setImageBitmap(cameraImage);
}
}
}
You can use the compress() method to save it in External storage.
You can try this
try
{
FileOutputStream out = new FileOutputStream(new File(Environment.getExternalStorageDirectory().toString() + "/bmp.png"));
cameraImage.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
catch (Exception e)
{
Toast.makeText(getBaseContext(),e.getMessage(), Toast.LENGTH_SHORT);
}
Also, you have to add uses permission <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Related
I am using the following code for clicking a photo on Button click.
package com.example.clickpic;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
int TAKE_PHOTO_CODE = 0;
public static int count=0;
private ImageView imageView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//here,we are making a folder named picFolder to store pics taken by the camera using this application
final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
File newdir = new File(dir);
newdir.mkdirs();
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button capture = (Button) findViewById(R.id.btnCapture);
capture.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// here,counter will be incremented each time,and the picture taken by camera will be stored as 1.jpg,2.jpg and likewise.
count++;
String file = dir+count+".jpg";
File newfile = new File(file);
try {
newfile.createNewFile();
} catch (IOException e) {}
Uri outputFileUri = Uri.fromFile(newfile);
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 1888);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1888 && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
The code works perfectly well but it just opens up the camera activity. What must I do so that on button click, it clicks a picture and saves it as well?
Right now, this just opens the camera app of the phone, and expects me to click the picture and click on OK. I don't want these things.
All I want is, when I click on the button from my app it should click a picture without expecting any additional input from me.
Edit
I have already tried to create a camera app of my own, but I ran into some issues.
That's why I am trying this approach. Camera API not working on KITKAT
All I want is, when I click on the button from my app it should click a picture without expecting any additional input from me. -
Its not achieved by Camera Intent like android.provider.MediaStore.ACTION_IMAGE_CAPTURE. You have to implement camera interface portion in your code without using native camera application of Device.
Look at portion of Building Camera App
I have written a camera class which takes picture, arranges the orientation (some devices takes photo horizontal as default) and saves the photo taken. You can check it from the link below:
Camera capture orientation on samsung devices in android
Edit: Sorry, savePhoto functions are not written in my example. Adding them now.
savePhoto function:
public void savePhoto(Bitmap bmp) {
imageFileFolder = new File(Environment.getExternalStorageDirectory(),
cc.getDirectoryName());
imageFileFolder.mkdir();
FileOutputStream out = null;
Calendar c = Calendar.getInstance();
String date = fromInt(c.get(Calendar.MONTH))
+ fromInt(c.get(Calendar.DAY_OF_MONTH))
+ fromInt(c.get(Calendar.YEAR))
+ fromInt(c.get(Calendar.HOUR_OF_DAY))
+ fromInt(c.get(Calendar.MINUTE))
+ fromInt(c.get(Calendar.SECOND));
imageFileName = new File(imageFileFolder, date.toString() + ".jpg");
try {
out = new FileOutputStream(imageFileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 70, out);
out.flush();
out.close();
scanPhoto(imageFileName.toString());
out = null;
} catch (Exception e) {
e.printStackTrace();
}
}
scanPhoto function:
public void scanPhoto(final String imageFileName) {
geniusPath = imageFileName;
msConn = new MediaScannerConnection(MyClass.this,
new MediaScannerConnectionClient() {
public void onMediaScannerConnected() {
msConn.scanFile(imageFileName, null);
}
#Override
public void onScanCompleted(String path, Uri uri) {
msConn.disconnect();
}
});
msConn.connect();
}
SavePhotoTask class:
class SavePhotoTask extends AsyncTask<byte[], String, String> {
#Override
protected String doInBackground(byte[]... jpeg) {
File photo = new File(Environment.getExternalStorageDirectory(),
"photo.jpg");
if (photo.exists()) {
photo.delete();
}
try {
FileOutputStream fos = new FileOutputStream(photo.getPath());
fos.write(jpeg[0]);
fos.close();
} catch (java.io.IOException e) {
}
return (null);
}
}
When I take a picture, the picture will saved on the SD.(This works very well)
But the picture won´t shows in the imageView. Do you have any idea?
package de.example.Camera;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Cam extends Activity {
private Uri fileUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.b_cam);
Button button2 = (Button) findViewById(R.id.photo);
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Start ActivityTwo
/*
* Intent intent = new Intent(getApplicationContext(),
* ActivityTwo.class); intent.putExtra("MyStringValue",
* editText1.getText().toString()); startActivity(intent);
*/
try {
PackageManager packageManager = getPackageManager();
boolean doesHaveCamera = packageManager
.hasSystemFeature(PackageManager.FEATURE_CAMERA);
if (doesHaveCamera) {
// start the image capture Intent
Intent intent = new Intent(
MediaStore.ACTION_IMAGE_CAPTURE);
// Get our fileURI
fileUri = getOutputMediaFile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(intent, 100);
}
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),
"There was an error with the camera.",
Toast.LENGTH_LONG).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
if (intent == null) {
// The picture was taken but not returned
Toast.makeText(
getApplicationContext(),
"The picture was taken and is located here: "
+ fileUri.toString(), Toast.LENGTH_LONG)
.show();
}else {
// The picture was returned
Bundle extras = intent.getExtras();
ImageView imageView1 = (ImageView) findViewById(R.id.imageView1);
imageView1.setImageBitmap((Bitmap) extras.get("data"));
}
}
}
}
private Uri getOutputMediaFile() throws IOException {
File mediaStorageDir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"DayTwentyNine");
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
.format(new Date());
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMG_" + timeStamp + ".jpg");
if (mediaFile.exists() == false) {
mediaFile.getParentFile().mkdirs();
mediaFile.createNewFile();
}
return Uri.fromFile(mediaFile);
}
}
In the manifest I have are the following:
uses-feature android:name="android.hardware.camera" android:required="false"
uses-permission android:name="android.permission.CAMERA"
uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
Here I have this peace of code that works fine the first function open the camera and take the picture and the second one place the image you took into an image view...
public void takePictu(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
photo3 = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo3);
imageView.buildDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo3.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
encodedImage = android.util.Base64.encodeToString(b, android.util.Base64.DEFAULT);
}
}
I have worked around for a week , and I cannot see why I can't get my thumbnail. I only need it , and not the actual image, and I read that it is convenient to get it through Mediastore.captureimage with no urifile passed to the intent .
My code :
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends Activity {
private ImageView image;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
image = (ImageView) findViewById(R.id.image);
}
public void vignette(View vue) {
Intent intention = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intention, 1);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
Uri imageUri = null;
if (data != null) {
if (data.hasExtra("data")) {
Bitmap vignette = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(vignette);
}
}
}
}
}
Actually, data is not null,
but hasExtra("data") gives null.
Though I can see
Intent { act=inline-data dat=content://media/external/images/media/8767 (has extras) }
... is there a way to get that extra !
Inorder to get bitmap from bitmap
Uri imageUri = data.getData();
Bitmap vignette = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
call this in your onActivityResult function this will give the bitmap
You can always resize the bitmap to your requirement
vignette =Bitmap.createScaledBitmap(vignette ,100,100, true);
image.setImageBitmap(vignette);
this will create a bitmap of 100*100
Hey I am new to android and eclipse environment.I've no idea of Java.I'm trying to create an app to open the camera of an android device.This is how my main activity.java looks like
package com.example.trycamera2;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
private Uri fileUri;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button_send);*****
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/xray");
dir.mkdirs();
File file = new File(dir, "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis()) + ".jpg");
fileUri = Uri.fromFile(file);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name
startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
}
});
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Bitmap tempBitmap = (Bitmap) data.getExtras().get("data");
FileOutputStream out;
try {
out = new FileOutputStream(fileUri.getPath());
tempBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.v("ManageImage-other", "another phone type");
e.printStackTrace();
}
// Image captured and saved to fileUri specified in the Intent
Toast.makeText(this, "Image saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
// User cancelled the image capture
} else {
// Image capture failed, advise user
}
}
}
}
There is a red mark under button_send in the star marked line...it shows an alternative action_settings instead of button_send....but when I replace with action_settings and run the launch is cancelled.Failed to install .apk on emulator..any help will be of great use.
Sounds like Android can't find your button in any of the layouts. Double check your layouts to make sure they're there.
If they are, just go to the Project menu at the top, and select Clean. Select your project, then click Okay. It will take moment to clean and build, but that might fix your issue.
I Have a activity that opens the Camera by starting ACTION_IMAGE_CAPTURE Intent:
Intent intent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
SimpleDateFormat dateformat = new SimpleDateFormat("ddMMyy");
File photo1 = new File(Environment
.getExternalStorageDirectory(), imageName);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo1));
startActivityForResult(intent, 5);
After starting this intent it opens the image capture screen and sometimes after clicking on the capture button it doesn't return to my app (onActivityResult) it enforce me to take an image another time again, and it doen't close this screen only if i hit the back button.
I put a break point in OnActivityResult when debugging and it doen't stop in this method.
Here is the sample application which gives option to select a image from either using camera or gallery and its also allows the option of cropping image. I hope this is what you exactly want.
Please see this https://github.com/lorensiuswlt/AndroidImageCrop
Its opensource download it and explore.
Here is my code for camera intent .It works perfectly ,you can try using it .
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class PlayMenuActivity extends Activity implements OnClickListener {
Intent intent;
ImageButton cameraBtn, galleryBtn, maleBtn, femaleBtn;
static Bitmap photo;
Dialog dialog;
static String gender;
MediaPlayer mp;
protected static final int PHOTO_PICKED = 0;
private static final int CAMERA_REQUEST = 1337;
private static final int SELECT_PHOTO = 100;
private static final String TEMP_PHOTO_FILE = "tempPhoto.jpg";
protected boolean circleCrop = true;
private final static String TAG = "GetImageFromGalleryActivity";
// values for scaling image
protected int outputX = 320;
protected int outputY = 480;
protected int aspectX = 2;
protected boolean scale = true;
protected int aspectY = 3;
protected boolean return_data = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("hello", "oncreate PlayMenu");
setContentView(R.layout.play_menu_screen);//setting layout
//Image Buttons on activity screen
cameraBtn = (ImageButton) findViewById(R.id.cameraBtn_id);
galleryBtn = (ImageButton) findViewById(R.id.galleryBtn_id);
cameraBtn.setOnClickListener(this);
galleryBtn.setOnClickListener(this);
// sound played when button clicked
mp = MediaPlayer.create(this, R.raw.click);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.cameraBtn_id:
// camera intent for starting camera
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra("crop", "true");
cameraIntent.putExtra("aspectX", aspectX);
cameraIntent.putExtra("aspectY", aspectY);
cameraIntent.putExtra("outputX", outputX);
cameraIntent.putExtra("outputY", outputY);
cameraIntent.putExtra("scale", scale);
cameraIntent.putExtra("category", "camera");
startActivityForResult(cameraIntent, CAMERA_REQUEST);
break;
case R.id.galleryBtn_id:
// calling GalleryActivity for picking image from gallery
intent = new Intent(PlayMenuActivity.this, GalleryActivity.class);
startActivity(intent);
break;
default:
break;
}
}
/* creates bitmap of the captured photo */
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Log.i("hello", "REQUEST cALL");
//if a camera request is made and resultcode matches then bitmap is created
if (requestCode == CAMERA_REQUEST || resultCode == Activity.RESULT_OK) {
Log.i("hello", "REQUEST cALL");
try {
Log.i("hello", "Try Call");
Bitmap bMap = (Bitmap) data.getExtras().get("data");//creating bitmap
photo = bMap;
Intent intent = new Intent(PlayMenuActivity.this,
ShowActivity.class);
intent.putExtra("category", "camera");//adding category selected ie camera
startActivity(intent);
} catch (Exception e) {
Log.i("hello", "Exception" + e.getMessage());
}
} else {
// Log.i("hello", "Else call");
Toast.makeText(PlayMenuActivity.this, "Picture NOt taken",
Toast.LENGTH_LONG).show();
}
} // fn
}// class
Hope this helps .
this is very late, but the issue here could be missing read/write permissions. I had this very issue myself and it had to do with me wanting to put the image file into my own app folder, to which the camera app had no access to.
To be safe, when sharing files betweens apps, consider using Environment.getExternalStoragePublicDirectory(), instead of Environment.getExternalStorageDirectory().