I am new to android and I am trying to make a part of my code to save image taken by my application that uses the default android camera. I want the image to be displayed in a different activity once I quit camera . Right now, if I don't save it, the image is displayed once the camera mode is quit. But if I try to save it too, the camera wont exit at all and the "OK" button does not respond.
I am trying to build an app that takes pictures and attaches it to email and sends it along with the GPS location data.So the "send-message" part of the switch-case is for that reason.
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.Picture:
File file = new File(Environment.getExternalStorageDirectory().getPath() + "/My Images/" + "bhe_app" + ".jpg");
Uri imageUri = Uri.fromFile(file);
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
i.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(i, cameraData);
break;
case R.id.SendMessage: //Sending message part
EditTextToString();
EmailIntent = new Intent(android.content.Intent.ACTION_SEND);
EmailIntent.putExtra(Intent.EXTRA_EMAIL,
new String[] { "myEmail#gmail.com" });
EmailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
MessageToBeReceived);
EmailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "#"+Lattitude_data +"," +Longitude_data);
// EmailIntent.setType("message/rfc822");
EmailIntent.setType("image/jpeg");
// EmailIntent.putExtra(Intent.EXTRA_STREAM, fileUri);
startActivity(Intent.createChooser(EmailIntent,
"Choose an Email client :"));
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setImageBitmap(bmp);
//iv is an image view in an activity where I display the image taken.
//bmp is defined as being Bitmap.
// final static int cameraData =0
}
}
You forgot to create directory you write image.
Add this line before you create file object.
File path = new File(Environment.getExternalStorageDirectory().getPath() + "/My Images/").
path.mkdirs();
Related
I am using an intent to send email with subject, content and attached images
everything works fine except some of the images don't get attached
File path for successfully attached photos is like:
content://media/external/images/media/14960
File path for Unsuccessfully attached photos is like:
content://com.android.providers.media.documents/document/image%3A14745
I am using this code
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.setType("message/rfc822");
//emailIntent.setType("application/image");
emailIntent.putExtra(Intent.EXTRA_EMAIL , new String[]{""});
emailIntent.putExtra(Intent.EXTRA_SUBJECT, mNotes.get(position).getTitle());
emailIntent.putExtra(Intent.EXTRA_TEXT , mNotes.get(position).getContent());
ArrayList<String[]> photos = StringManipulation.imgDeserialize(mNotes.get(position).getImgUrls());
for (String[] photo : photos){
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(photo[0]));
}
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
How can i made all the photos get attached to the email?
I got this Uris by taking permissions for CAMERA, READ and WRITE EXTERNAL STORAGE
//.... onCreate...
//initialize the textview for starting the camera
TextView takePhoto = (TextView) view.findViewById(R.id.tvTakeCameraPhoto);
takePhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: starting camera.");
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, Permissions.CAMERA_REQUEST_CODE);
}
});
//Initialize the textview for choosing an image from memory
TextView selectPhoto = (TextView) view.findViewById(R.id.tvChoosePhotoFromMemory);
selectPhoto.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: accessing phones memory.");
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, Permissions.PICK_FILE_REQUEST_CODE);
}
});
//.................
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
/*
Results when taking a new image with camera
*/
if(requestCode == Permissions.CAMERA_REQUEST_CODE && resultCode == Activity.RESULT_OK){
Log.d(TAG, "onActivityResult: done taking a picture.");
//get the new image bitmap
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: received bitmap: " + bitmap);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getActivity(), bitmap);
// CALL THIS METHOD TO GET THE ACTUAL PATH
File takenPhotoFile = new File(tempUri.toString());
mOnPhotoReceived.getImagePath(takenPhotoFile.getPath());
getDialog().dismiss();
}
/*
Results when selecting new image from phone memory
*/
if(requestCode == Permissions.PICK_FILE_REQUEST_CODE && resultCode == Activity.RESULT_OK){
Log.d(TAG, "onActivityResult: done choosing image");
Uri selectedImageUri = data.getData();
File file = new File(selectedImageUri.toString());
Log.d(TAG, "onActivityResult: images: " + file.getPath());
//send the bitmap and fragment to the interface
mOnPhotoReceived.getImagePath(file.getPath());
getDialog().dismiss();
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
then passing the listener to the activity.
First, your app on its own needs permissions to read the content identified by those Uri values. You do not indicate where and how you get those Uri values, but you only have a short time to use them, in general. If you do not have read access to the content, you will be out of luck.
Second, add this line before the startActivity() call:
emailIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
This passes your read permission along to whatever app processes this Intent.
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);
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 am learning android and working on an application to takes pictures and send them through email. I have got the picture in ImageView in the code below, but am not sure how to send this picture as an email attachment, without saving the picture to file on the device.
Ideally i would like to know if that is possible? If yes can you point me the correct direction on how to implement the same. Also(optionally) if the picture can be compressed.
public class EmailPic extends Activity implements OnClickListener{
ImageButton ibEmail;
Button bEmail;
ImageView ivEmail;
Intent intentEmail;
Bitmap bmpEmail;
final static int picData = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pic_email);
initializeVars();
InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
bmpEmail = BitmapFactory.decodeStream(is);
}
private void initializeVars() {
ibEmail = (ImageButton)findViewById(R.id.ibTakePicEmail) ;
ivEmail = (ImageView)findViewById(R.id.ivPicEmail);
bEmail = (Button) findViewById(R.id.bSendPicEmail);
bEmail.setOnClickListener(this);
ibEmail.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ibTakePicEmail:
intentEmail = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intentEmail,picData);
break;
case R.id.bSendPicEmail:
String message = "email Body";
String[] recipients = new String[]{"mymail.com"};
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("application/image");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,recipients);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,message);
startActivity(emailIntent);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Bundle ext = data.getExtras();
bmpEmail = (Bitmap)ext.get("data");
//Log.d("StatusActivity","bmpEmail >>"+bmpEmail);
ivEmail.setImageBitmap(bmpEmail);
}
}
}
Try out as below:
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setType("image/*");
Uri uri = Uri.parse("android.resource://your package name/"+R.drawable.ic_launcher);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
shareIntent.putExtra(android.content.Intent.EXTRA_EMAIL,recipients);
shareIntent.putExtra(Intent.EXTRA_TEXT, message);
startActivity(Intent.createChooser(shareIntent, "Send your image"));
EDITED:
Declare the File variable
File pic;
In your OnActivityResult() apply changes as below:
Bundle ext = data.getExtras();
bmpEmail = (Bitmap)ext.get("data");
try {
File root = Environment.getExternalStorageDirectory();
if (root.canWrite()){
pic = new File(root, "pic.png");
FileOutputStream out = new FileOutputStream(pic);
bmpEmail.compress(CompressFormat.PNG, 100, out);
out.flush();
out.close();
}
} catch (IOException e) {
Log.e("BROKEN", "Could not write file " + e.getMessage());
}
And in your send email code add the line
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(pic));
So, You want to capture the image from the ImageView, compress it and then attach.
Basically the process is :
Get the Image from the ImageView.
Convert to Bitmap.
Save it.(You have to do it in any case, if you want to attach it)
Hopefully you can delete it afterwards.
Attach to email Intent.
First of all get the cached bitmap of the ImageView
Bitmap myBitmap = yourImageView.getDrawingCache();
This will return the cached bitmap from the ImageView.
Compress it and save
URI FILENAME; //URI For the ImageView, we need earlier to send
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
myBitmap.compress(Bitmap.CompressFormat.PNG, 0, fos);
fos.close();
Create your Send Intent
String message = "email Body";
String[] recipients = new String[]{"mymail.com"};
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("application/image");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,recipients);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Subject");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,message);
emailIntent.putExtra(Intent.EXTRA_STREAM, FILENAME); //this line is added to your code
startActivity(emailIntent);
You can delete the image afterward if you need to.
I have read this link :Open an image in Android's built-in Gallery app programmatically Get/pick an image from Android's built-in Gallery app programmatically, and the code looks well.
It results with following image: http://i.stack.imgur.com/vz3S8.png, but this is not the result I want.
I want to open the gallery similar to: http://i.stack.imgur.com/ZoUvU.png.
I want to choose the pic form the folder gallery.
Do you know how to modify the code?
I used:
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.android.gallery", "com.android.camera.GalleryPicker"));
// intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
Log.i("aa","adafdsfa");
startActivityForResult(intent, 1);
Through I get the folder gallery, but I cannot get the pic path.
File dir = new File(Environment.getExternalStorageDirectory().toString() + "/sdcard/yourfolder");
Log.d("File path ", dir.getPath());
String dirPath=dir.getAbsolutePath();
if(dir.exists() && dir.isDirectory()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
// tells your intent to get the contents
// opens the URI for your image directory on your sdcard
//its upto you what data you want image or video.
intent.setType("image/*");
// intent.setType("video/*");
intent.setData(Uri.fromFile(dir));
// intent.setType("media/*");
// intent.
startActivityForResult(intent, 1);
}
else
{
showToast("No file exist to show");
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (data==null) {
showToast("No image selected");
//finish();
}
else
{
Uri selectedImageUri = data.getData();
// String filemanagerstring = selectedImageUri.getPath();
//MEDIA GALLERY
String selectedImagePath = getPath(selectedImageUri);
if(selectedImagePath!=null)
{
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(selectedImageUri);
startActivity(intent);
}
else
{
showToast("Image path not correct");
}
}
}
}