Share an image from drawable folder in android


Hi All, Today in android programming we are going to learn how to share an image which is placed inside the drawable folder to otherApps like Gmail or Whatsapp, In this method in which i am showing there is no need of special permissions, usually this is done by first writing a copy of the image to external memory and then sharing, instead i used a better approach. For this we want to implement FileProvider for supporting Android versions above Nougat.You can get enough tutorials on how to implement FileProvider on web from here
After implementing file provider as shown in above link we can use the below code using FileProvider class to easily share images from drawable folder. kudos developers:)
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.my_super_sample_image);
String path = getExternalCacheDir() + "/shareimage.jpg";
java.io.OutputStream out = null;
java.io.File file = new java.io.File(path);
try {
out = new java.io.FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);//Change JPEG to PNG if necessary
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
path = file.getPath();
Uri bmpUri = FileProvider.getUriForFile(
getBaseContext(),
getApplicationContext()
.getPackageName() + ".provider", file);
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("image/jpeg"); //Change JPEG to PNG if necessary
shareIntent.putExtra(Intent.EXTRA_TEXT, "Sample Text");
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
startActivity(shareIntent);
Share on Google Plus

About Admin

I am a Java and Android developer and a science enthusiast.I Like to explain complex things in simple language so anybody even without a graduation in computer science or Electronics can understand the concepts easily.

0 comments:

Post a Comment