I want to share the edited photo to a social media site after editing it using PhotoEditorSDK Android version, so I created a shareImage() function.
However I am not sure how to reference the edited image from the PhotoEditorSDK in the share function. Currently the code listed below I just add a dummy image of the image taken from drawable resources.
Also currently the share button I placed in PhotoEditorSDK photoeditor view keeps crashing on press.
public class PhotoEditorActivity extends Activity implements PermissionRequest.Response {
private static final String FOLDER = "ArtCam";
public static int CAMERA_PREVIEW_RESULT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
SettingsList settingsList = new SettingsList();
settingsList.getSettingsModel(EditorLoadSettings.class)
.setImageSourcePath(selectedImagePath, true) // Load with delete protection true!
.getSettingsModel(EditorSaveSettings.class)
.setExportDir(Directory.DCIM, FOLDER)
.setExportPrefix("result_")
.setSavePolicy(
EditorSaveSettings.SavePolicy.KEEP_SOURCE_AND_CREATE_ALWAYS_OUTPUT
);
new PhotoEditorBuilder(this)
.setSettingsList(settingsList)
.startActivityForResult(this, CAMERA_PREVIEW_RESULT);
shareImage();
}
private void shareImage() {
Intent shareIntent;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/Share.png";
OutputStream out = null;
File file = new File(path);
try {
out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
path = file.getPath();
Uri bmpUri = Uri.parse("file://" + path);
shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.putExtra(Intent.EXTRA_TEXT, "#" + getPackageName());
shareIntent.setType("image/png");
startActivity(Intent.createChooser(shareIntent, "Share with"));
}
Please look at the demo code here https://github.com/imgly/pesdk-android-demo/blob/master/app/src/main/java/com/photoeditorsdk/android/app/MainActivity.java
You have to wait for onActivityResult to get the resultPath
#Override
protected void onActivityResult(int requestCode, int resultCode, android.content.Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && requestCode == CAMERA_PREVIEW_RESULT) {
String resultPath = data.getStringExtra(ImgLyIntent.RESULT_IMAGE_PATH);
if (resultPath != null) {
// Add result file to Gallery
sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(resultPath))));
}
//TODO: Share the resultPath file
} else if (resultCode == RESULT_CANCELED && requestCode == CAMERA_PREVIEW_RESULT && data != null) {
String sourcePath = data.getStringExtra(ImgLyIntent.SOURCE_IMAGE_PATH);
Toast.makeText(PESDK.getAppContext(), "Editor canceled, sourceType image is:\n" + sourcePath, Toast.LENGTH_LONG).show();
}
}
Related
I have no experience in coding and i am just creating a app from tutorials in android studio. I have come a very long way in creating the app. I have implemented the code for selecting a image from the devive gallery and now i wonder how i can set that picture as a Firebase PhotoURL for the current user?
I have implemented that while I was trying firebase. Hope this would do your work.
getImageFromMobile is set to the onClick Method of ImageButton which I am using to set Image to.
public void getImageFromMobile(View view) {
if(ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{
android.Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
}
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/");
startActivityForResult(intent , galleryRequestCode);
}
private void postDataToFirebase() {
mProgressDialog.setMessage("Posting the Blog to Firebase");
mProgressDialog.setCancelable(false);
final String titleValue = mPostTitle.getText().toString();
final String description = mPostDescription.getText().toString();
if((!TextUtils.isEmpty(titleValue))&& (!TextUtils.isEmpty(description)) && bitmap != null)
{
mProgressDialog.show();
StorageReference filePath = mStorage.child("Blog_Images").child(imagePathName);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 20, bytes);
String path = MediaStore.Images.Media.insertImage(PostActivity.this.getContentResolver(), bitmap, imagePathName, null);
Uri uri = Uri.parse(path);
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference newPost = mDatabaseReference.push();
newPost.child("Title").setValue(titleValue);
newPost.child("Desc").setValue(description);
newPost.child("imageUrl").setValue(downloadUrl.toString());
Toast.makeText(PostActivity.this, "Data Posted Successfully to Firebase server", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
Intent intent = new Intent(PostActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == galleryRequestCode && resultCode == RESULT_OK){
Uri imageUri = data.getData();
imagePathName = imageUri.getLastPathSegment();
Log.i("ImagePathName",imagePathName);
Toast.makeText(this, "ImagePathNameto be Checked" + imagePathName, Toast.LENGTH_SHORT).show();
try {
bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
imageButton.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I need to push an intent to default camera application to make it take a photo, save it and return an URI. Is there any way to do this?
private static final int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}
Try the following I found here
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 0) {
String result = data.toURI();
// ...
}
}
It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.
Request this permission on the AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
On your Activity, start by defining this:
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
Then fire this Intent in an onClick:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
Add the following support method:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
Then receive the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)), which is different from the code from developer.android.com. The original code gave me a FileNotFoundException.
I found a pretty simple way to do this. Use a button to open it using an on click listener to start the function openc(), like this:
String fileloc;
private void openc()
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = null;
try
{
f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
fileloc = Uri.fromFile(f)+"";
Log.d("texts", "openc: "+fileloc);
startActivityForResult(takePictureIntent, 3);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 3 && resultCode == RESULT_OK) {
Log.d("texts", "onActivityResult: "+fileloc);
// fileloc is the uri of the file so do whatever with it
}
}
You can do whatever you want with the uri location string. For instance, I send it to an image cropper to crop the image.
Try the following I found Here's a link
If your app targets M and above and declares as using the CAMERA permission which is not granted, then attempting to use this action will result in a SecurityException.
EasyImage.openCamera(Activity activity, int type);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
#Override
public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
//Some error handling
}
#Override
public void onImagesPicked(List<File> imagesFiles, EasyImage.ImageSource source, int type) {
//Handle the images
onPhotosReturned(imagesFiles);
}
});
}
Call the camera through intent, capture images, and save it locally in the gallery.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
someActivityResultLauncher.launch(cameraIntent);}
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
bitmap = (Bitmap) Objects.requireNonNull(result.getData()).getExtras().get("data");
}
imageView.setImageBitmap(bitmap);
saveimage(bitmap);
}
private void saveimage(Bitmap bitmap){
Uri images;
ContentResolver contentResolver = getContentResolver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
images = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
}else {
images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, System.currentTimeMillis() +".jpg");
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "images/*");
Uri uri = contentResolver.insert(images, contentValues);
try {
OutputStream outputStream = contentResolver.openOutputStream(Objects.requireNonNull(uri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
Objects.requireNonNull(outputStream);
//
}catch (Exception e){
//
e.printStackTrace();
}
}
try this code
Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(photo, CAMERA_PIC_REQUEST);
I'm completely news on android thing and unfortunately with little few time to learn it by the right way, I have a work to release.
The problem is: I need to take a picture and process her with an algorithm that I made.
I did it by the easiest way that I could find, I know it looks like really trahsie for those who really get android (sorry)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
takePic();
protected void takePic(){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, 100);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bundle extras = data.getExtras();
mImageBitmap = (Bitmap) extras.get("data");
Algorithm(mImageBitmap)
But it doesn't process, it takes a photo, ask to save or cancell and leaves the application, I have already made by different ways (creating a new activity), but nothing seems to work
Heres how I did it
To go to the camera:
Somewhere, declaire a fileUri variable and hold onto it
Uri fileUri;
final int TAKE_PICTURE=100;//this can be any int, really
public void goToCamera(){
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo;
try
{
// place where to store camera taken picture
photo = this.createTemporaryFile("picture", ".jpg");
Log.v(TAG, "Here(after createTempFile)");
photo.delete();
}
catch(Exception e)
{
Log.v(TAG, "Can't create file to take picture!" + e.getMessage());
Toast.makeText(context, "Please check SD card!", Toast.LENGTH_SHORT).show();
return;
}
fileUri = Uri.fromFile(photo);
intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
//Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, TAKE_PICTURE);
}
Then to retreive the image
protected void onActivityResult(int requestCode, int resultCode, Intent data){
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK){
this.getContentResolver().notifyChange(uri, null);
ContentResolver cr = this.getContentResolver();
Bitmap bitmap;
try
{
BitmapFactory.Options ops = new BitmapFactory.Options();
ops.inSampleSize = 4;
bitmap = BitmapFactory.decodeFile(uri.getPath().toString(), ops);
}
catch (Exception e)
{
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT).show();
Log.d(TAG, "Failed to load", e);
}
}
}
The create temp file mentioned above:
private File createTemporaryFile(String part, String ext) throws Exception
{
File tempDir= Environment.getExternalStorageDirectory();
tempDir=new File(tempDir.getAbsolutePath()+"/.temp/");
Log.i(TAG, tempDir.toString());
if(!tempDir.exists())
{
Log.i(TAG, "Dir doesnt exist");
tempDir.mkdirs();
}
return File.createTempFile(part, ext, tempDir);
}
I realize this isn't probably as simple as you were hoping for, but this approach seemed to be as flexible and compatible as possible. Let me know if I left anything else out
I have already tried this code, but i didn't saw photo shared in my account.
File file = new File("sdcard/1346249742258.jpg");
String photoUri = null;
photoUri = file.getAbsolutePath();
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
.setText("Sharing an image on Google!").setType("image/jpeg")
.setStream(Uri.parse(photoUri)).getIntent()
.setPackage("com.google.android.apps.plus");
startActivity(shareIntent);
The Google+ app only supports content:// URIs. You will need to use the MediaStore API for this purpose.
File tmpFile = new File("/path/to/image");
final String photoUri = MediaStore.Images.Media.insertImage(
getContentResolver(), tmpFile.getAbsolutePath(), null, null);
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
.setText("Hello from Google+!")
.setType("image/jpeg")
.setStream(Uri.parse(photoUri))
.getIntent()
.setPackage("com.google.android.apps.plus");
Integrate ForGooglePlus Activity in your code and put URL(imageUrl) ,Description(description text) and contentUrl(URL) for the same.
Note : bellow code also worked in my app.
public class ForGooglePlus extends Activity
{
private String imageUrl, description, contentUrl;
private Context mContext;
private int REQUEST_FOR_GOOGLE_PLUS = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
mContext = this;
imageUrl = getIntent().getStringExtra("URL");
description = getIntent().getStringExtra("Description");
contentUrl = getIntent().getStringExtra("contentUrl");
if (isPackageInstalled("com.google.android.apps.plus", mContext)) {
if (imageUrl == null) {
imageUrl = "";
}
if (description == null) {
description = "";
}
// Intent shareIntent = new PlusShare.Builder(this)
// .setType("image/jpeg")
// .setText(description)
// .setStream(getUriFromUrl(imageUrl))
// .setContentUrl(Uri.parse(contentUrl))
// .getIntent();
Uri uri = getUriFromUrl(imageUrl);
if (uri != null) {
Intent shareIntent = ShareCompat.IntentBuilder
.from(ForGooglePlus.this)
.setText(description + "\n" + contentUrl)
.setType("image/jpeg").setStream(uri).getIntent()
.setPackage("com.google.android.apps.plus");
startActivityForResult(shareIntent, REQUEST_FOR_GOOGLE_PLUS);
} else {
Intent shareIntent = ShareCompat.IntentBuilder
.from(ForGooglePlus.this)
.setText(description + "\n" + contentUrl)
.setType("image/jpeg").getIntent()
.setPackage("com.google.android.apps.plus");
startActivityForResult(shareIntent, REQUEST_FOR_GOOGLE_PLUS);
}
} else {
Toast.makeText(mContext, "Application not found", Toast.LENGTH_LONG)
.show();
finish();
}
}
public Uri getUriFromUrl(String thisUrl) {
try {
Bitmap inImage = ImageLoader.getInstance().loadImageSync(thisUrl);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(
mContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
private boolean isPackageInstalled(String packagename, Context context) {
PackageManager pm = context.getPackageManager();
try {
pm.getPackageInfo(packagename, PackageManager.GET_ACTIVITIES);
return true;
} catch (NameNotFoundException e) {
return false;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_FOR_GOOGLE_PLUS) {
if (resultCode == RESULT_OK) {
finish();
} else {
Toast.makeText(mContext,
mContext.getString(R.string.msg_gp_cancel),
Toast.LENGTH_LONG).show();
finish();
}
}
}
}
I am also posting image on google plus through android using intent i am taking screen shot of device and posting it on google plus, i used your code i am getting exception FileNotFoundException() and as you mention to use absolute path i got error,
The method getAbsolutePath() is undefined for the type String
my code is given below
please suggest me correction in code
package com.testproject;
import java.io.File;
import java.io.FileNotFoundException;
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.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
public class TestProjectActivity extends Activity {
private Button share_btn = null;
private String url=null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
share_btn = (Button)findViewById(R.id.share_btn);
share_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent=new Intent(TestProjectActivity.this,ShareDialogActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent, 1);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String url =takeScreenShot();
super.onActivityResult(requestCode, resultCode, data);
switch (resultCode) {
case 1:
String share = data.getExtras().getString("NAME");
if(share!=null && share.equalsIgnoreCase("Share with Instagram")){
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("image/jpg");
i.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
startActivity(Intent.createChooser(i, "Share Image"));
}
if(share!=null && share.equalsIgnoreCase("Share with GooglePlus")){
Intent shareIntent = new Intent(Intent.ACTION_SEND);
File tmpFile = new File(url);
String photoUri=null;
photoUri = url.getAbsolutePath();
try {
photoUri = MediaStore.Images.Media.insertImage(
getContentResolver(), tmpFile.getAbsolutePath(), null, null);
shareIntent = ShareCompat.IntentBuilder.from(this)
.setText("Hello from Google+!")
.setType("image/jpeg")
.setStream(Uri.parse(photoUri))
.getIntent()
.setPackage("com.google.android.apps.plus");
startActivity(shareIntent);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
break;
}
}
public String takeScreenShot(){
try{
RelativeLayout view = (RelativeLayout)findViewById(R.id.icflag_layout);
View v1 = view.getRootView();
System.out.println("Root View : "+v1);
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
url =MediaStore.Images.Media.insertImage(getContentResolver(), bm,"screeshot.jpg", 1233+ ".jpg Card Image");
}
catch(OutOfMemoryError e){
}
return url;
}
}
Thank you and regards
Nitin
Don't use absolute path.
OnActivityResult() use this after capturing image from camera.
Uri photoUri = intent.getData();
Intent shareIntent = ShareCompat.IntentBuilder.from(this)
.setText("Hello From Google+!")
.setType("image/jpeg")
.setStream(photoUri)
.getIntent()
.setPackage("com.google.android.apps.plus");
startActivity(shareIntent);
This is working for me.
HEy Deepika you are getting file nor found exception because that google plus app is not present on the device the way you have coded is just to start the native app from the device
it will work only if the native ap is actully present
otherway is to have google plus sdk which is small jar file with that you can share image
https://developers.google.com/+/mobile/android/
You can share image using below api's. For detailed steps check tutorial
http://androidsrc.net/integrating-google-plus-sign-in-into-your-android-application/
/**
* API to process media post request start activity with MIME type as video
* and image
*/
private void processShareMedia() {
Intent photoPicker = new Intent(Intent.ACTION_PICK);
photoPicker.setType("video/*, image/*");
startActivityForResult(photoPicker, PICK_MEDIA_REQUEST_CODE);
}
/**
* Handle results for your startActivityForResult() calls. Use requestCode
* to differentiate.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PICK_MEDIA_REQUEST_CODE) {
// If picking media is success, create share post using
// PlusShare.Builder
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
ContentResolver cr = this.getContentResolver();
String mime = cr.getType(selectedImage);
PlusShare.Builder share = new PlusShare.Builder(this);
share.setText("Hello from AndroidSRC.net");
share.addStream(selectedImage);
share.setType(mime);
startActivityForResult(share.getIntent(),
SHARE_MEDIA_REQUEST_CODE);
}
}
}
I need to push an intent to default camera application to make it take a photo, save it and return an URI. Is there any way to do this?
private static final int TAKE_PICTURE = 1;
private Uri imageUri;
public void takePhoto(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ImageView imageView = (ImageView) findViewById(R.id.ImageView);
ContentResolver cr = getContentResolver();
Bitmap bitmap;
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(bitmap);
Toast.makeText(this, selectedImage.toString(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
.show();
Log.e("Camera", e.toString());
}
}
}
}
Try the following I found here
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 0) {
String result = data.toURI();
// ...
}
}
It took me some hours to get this working. The code it's almost a copy-paste from developer.android.com, with a minor difference.
Request this permission on the AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
On your Activity, start by defining this:
static final int REQUEST_IMAGE_CAPTURE = 1;
private Bitmap mImageBitmap;
private String mCurrentPhotoPath;
private ImageView mImageView;
Then fire this Intent in an onClick:
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (cameraIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
Log.i(TAG, "IOException");
}
// Continue only if the File was successfully created
if (photoFile != null) {
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(cameraIntent, REQUEST_IMAGE_CAPTURE);
}
}
Add the following support method:
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, // prefix
".jpg", // suffix
storageDir // directory
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
Then receive the result:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
try {
mImageBitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath));
mImageView.setImageBitmap(mImageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
What made it work is the MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse(mCurrentPhotoPath)), which is different from the code from developer.android.com. The original code gave me a FileNotFoundException.
I found a pretty simple way to do this. Use a button to open it using an on click listener to start the function openc(), like this:
String fileloc;
private void openc()
{
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = null;
try
{
f = File.createTempFile("temppic",".jpg",getApplicationContext().getCacheDir());
if (takePictureIntent.resolveActivity(getPackageManager()) != null)
{
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,FileProvider.getUriForFile(profile.this, BuildConfig.APPLICATION_ID+".provider",f));
fileloc = Uri.fromFile(f)+"";
Log.d("texts", "openc: "+fileloc);
startActivityForResult(takePictureIntent, 3);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 3 && resultCode == RESULT_OK) {
Log.d("texts", "onActivityResult: "+fileloc);
// fileloc is the uri of the file so do whatever with it
}
}
You can do whatever you want with the uri location string. For instance, I send it to an image cropper to crop the image.
Try the following I found Here's a link
If your app targets M and above and declares as using the CAMERA permission which is not granted, then attempting to use this action will result in a SecurityException.
EasyImage.openCamera(Activity activity, int type);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
EasyImage.handleActivityResult(requestCode, resultCode, data, this, new DefaultCallback() {
#Override
public void onImagePickerError(Exception e, EasyImage.ImageSource source, int type) {
//Some error handling
}
#Override
public void onImagesPicked(List<File> imagesFiles, EasyImage.ImageSource source, int type) {
//Handle the images
onPhotosReturned(imagesFiles);
}
});
}
Call the camera through intent, capture images, and save it locally in the gallery.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
someActivityResultLauncher.launch(cameraIntent);}
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK) {
bitmap = (Bitmap) Objects.requireNonNull(result.getData()).getExtras().get("data");
}
imageView.setImageBitmap(bitmap);
saveimage(bitmap);
}
private void saveimage(Bitmap bitmap){
Uri images;
ContentResolver contentResolver = getContentResolver();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
images = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
}else {
images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, System.currentTimeMillis() +".jpg");
contentValues.put(MediaStore.Images.Media.MIME_TYPE, "images/*");
Uri uri = contentResolver.insert(images, contentValues);
try {
OutputStream outputStream = contentResolver.openOutputStream(Objects.requireNonNull(uri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
Objects.requireNonNull(outputStream);
//
}catch (Exception e){
//
e.printStackTrace();
}
}
try this code
Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(photo, CAMERA_PIC_REQUEST);