Sharing a file via Mediastore - android

I am trying to insert a file in MediaStore and then share the same file using the uri generated.
For Inserting the file
ImageView image = (ImageView) findViewById(R.id.image);
Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
String fileName = "myFile.jpg";
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bytes);
File enternalStroageDir = Environment.getExternalStorageDirectory();
File file = new File(enternalStroageDir + File.separator + fileName);
FileOutputStream fileOutputStream = null;
try {
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(bytes.toByteArray());
ContentResolver cr = getContentResolver();
String imagePath = file.getAbsolutePath();
String name = file.getName();
String description = "My bitmap created by Android-er";
String savedURL = MediaStore.Images.Media
.insertImage(cr, imagePath, name, description);
Now, the insert is working fine as I checked in the gallery.
Futher, to share the same image, I add the following code.
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, savedURL);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(Intent.createChooser(intent, "SendText"));
However, when I choose any application that are suggested in the chooser, the sharing of file gets failed.
Any help will be appreciated.

Related

How to compress a Bitmap when not saved

I am getting picture from a layout and do not want to save it. I want to share it directly through intent ACTION_SEND service. when I send it gives exception Transaction Too many Large: data parcel size 2315980 bytes
Here is my code snippet
View myview = (View) findViewById(R.id.mylayout);
Bitmap mypicture = getBitmapFromView(myview);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra("", mypicture);
intent.setType("image/jpeg");
startActivity(intent);
I want to share it directly through intent ACTION_SEND service
That is not an option. EXTRA_TEXT holds text. EXTRA_STREAM holds a Uri. Neither of those is a Bitmap.
Here is my code snippet
Your extra is pointless, as no ACTION_SEND activities will be looking for an extra with an empty key.
you can save your bitmap to a file, then share the uri/link to that file.
public static File saveBitmapInternal(Context context, Bitmap bitmap) {
File imagePath = new File(context.getFilesDir(), "images");
if (!imagePath.exists() && !imagePath.mkdirs()) {
print("Make dir failed");
}
return saveBitmap(bitmap, "preview.png", imagePath);
}
private static File saveBitmap(Bitmap bitmap, String filename, File root) {
print(String.format("Saving %dx%d bitmap to %s.", bitmap.getWidth(), bitmap.getHeight(), filename));
final File file = new File(root, filename);
if (file.exists()) {
file.delete();
}
try {
final FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 99, out);
out.flush();
out.close();
return file;
} catch (final Exception e) {
print("Exception!" + e);
}
return null;
}
then to share it,
// Uri uri = Uri.fromFile(file);
Uri uri = FileProvider.getUriForFile(context,
context.getString(R.string.file_provider_authority),
file);
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.putExtra(Intent.EXTRA_TEXT, shareText);
context.startActivity(Intent.createChooser(intent, "Share media"));
you need to set up the file provider in your manifest (refer to https://developer.android.com/reference/android/support/v4/content/FileProvider.html). you can create another question if you have queries regarding the fileprovider.

Share Image from url

I am tring to share an image which i fetch from Json. After a number of attempts i finally concluded with this code. It works well till i open whatsapp and select the contact i want to share, the image doesnt load from there and when i click on submit, it says sharing failed.
Drawable drawable1 = imageViewPreview.getDrawable();
Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.id.image_preview);
File file = new File(SlideshowDialogFragment.this.getCacheDir(), String.valueOf(largeIcon + ".png"));
// FileOutputStream fOut = new FileOutputStream(file);
// largeIcon.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
file.setReadable(true, false);
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("image/png");
startActivity(intent);
if i remove the comments
FileOutputStream fOut = new FileOutputStream(file);
will show error message and i have to add try/catch then, the app crashes saying Nullpoint exception
Try this code:
Bitmap bitmap = mBitmap;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "photo.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/photo.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));

Sharing image preview is wrong

When I try to share an screenshot via the Samsung email app the preview of the image I am sending is wrong. It happens only with the Samsung email app.
Here is my code:
-------here I am taking a screenshot-----------
String mPath = "";
try {
// image naming and path to include sd card appending name you choose for file
mPath = Environment.getExternalStorageDirectory().toString() + "/" + "share" + ".jpeg";
// create bitmap screen capture
View v1 = getActivity().getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
-------sending a screen shot via intent-----------
Uri imageUri = Uri.parse(sorcUrl);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(intent, "Share"));
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}

Sharing image from resources into intent Xamarin android

I am trying to share image from resources with other apps (like Viber or Facebook).
I used the code below to try and do this, but it is failing:
Bitmap bitmapToShare = BitmapFactory.DecodeResource(Application.Context.Resources, Resource.Drawable.A1);
Java.IO.File pictureStorage = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures);
Java.IO.File noMedia = new Java.IO.File(pictureStorage, ".nomedia");
if (!noMedia.Exists())
noMedia.Mkdirs();
string imageName = "shared_image" + System.DateTime.Now.ToBinary() + ".Jpeg";
Stream output = Application.Context.OpenFileOutput(imageName,FileCreationMode.WorldReadable);
bitmapToShare.Compress(Bitmap.CompressFormat.Jpeg, 100, output);
output.Flush();
output.Close();
Java.IO.File file = new Java.IO.File(noMedia, imageName);
shareIntent.SetType("image/*");
shareIntent.PutExtra(Intent.ExtraStream, Uri.FromFile(file));
shareIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
StartActivity(Intent.CreateChooser(shareIntent,"Share with"));
For what it's worth, the file is not saved after (output.close;). Why is this failing?

Attach image to ACTION_SEND then delete after

I'm creating an ACTION_SEND intent in android and attaching an image file with the following code:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/html");
intent.putExtra(Intent.EXTRA_EMAIL, "");
intent.putExtra(Intent.EXTRA_SUBJECT, "Receipt From: XXX");
intent.putExtra(Intent.EXTRA_TEXT, message);
byte[] b = Base64.decode(signature, Base64.DEFAULT); //Where signature is a base64 encoded string
final Bitmap mBitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
String path = Images.Media.insertImage(getContentResolver(), mBitmap, "signature", null);
Uri sigURI = Uri.parse(path);
intent.putExtra(Intent.EXTRA_STREAM, sigURI);
startActivity(Intent.createChooser(intent, "Send Email"));
This works, the image is attached to the email. However I'm having trouble deleting the image afterwords. The images are getting stored in the DCIM\Camera folder with a large number as the file name.
I've tried
File tempFile = File(getRealPathFromURI(sigURI)); //a subroutine which gives me the full path
tempFile.delete();
tempFile.delete returns true, however the file is still there.
One odd thing I noticed is that the image saved is of file size 0 and appears empty both before and after I try to delete.
How do I properly delete this image after sending it with the email? Or is there an alternative way of attaching the image without saving it?
Also, not the main question here but if you could include how to change the name of the image/attachment from 1375729812685.jpg (or what ever the number may be) to something else, I'de appreciate it.
As a last note, I've been testing on an HTC Evo if it makes any difference.
I have found a solution for anyone who is interested.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_EMAIL, new String[]{});
intent.putExtra(android.content.Intent.EXTRA_CC, new String[ {"test#test.net"});
intent.putExtra(Intent.EXTRA_SUBJECT, "Receipt From: " + receipt[1]);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "IMG_" + timeStamp + "_";
File albumF = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Receipt");
if (albumF != null) {
if (! albumF.mkdirs()) {
if (! albumF.exists()){
Log.d("CameraSample", "failed to create directory");
return;
}
}
}
File imageF = File.createTempFile(imageFileName, ".jpg", albumF);
byte[] b = Base64.decode(sig, Base64.DEFAULT);
if (b.length > 0) {
Bitmap mBitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
FileOutputStream ostream = new FileOutputStream(imageF);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, ostream);
ostream.flush();
ostream.close();
Uri fileUri = Uri.fromFile(imageF);
intent.putExtra(Intent.EXTRA_STREAM, fileUri);
}
intent.putExtra(Intent.EXTRA_TEXT, message);
intent.setType("message/rfc822");
startActivity(Intent.createChooser(intent, "Send Email Using"));

Categories

Resources