Reputation: 1032
I have a bitmap image in a view flipper and I need to show the share menu in Action bar. Once I click on share icon, should open up a share options and save to Gallery. Topic - Share and Save Options - Save to Gallery, and default share options like GMAIL, Hangouts, etc.
I was able to create the menu:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.history_menu, menu);
MenuItem item = menu.findItem(R.id.menu_item_share);
return true;
}
I am able to get the Bitmap image from flipper:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_share:
ImageView image = (ImageView) flipper.getCurrentView();
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
/*Need to know how to share and save image*/
return true;
default:
return false;
}
}
I need to know whether we have any default Android share and save layout, which will show the above options, or do I have to create a custom layout?
Upvotes: 0
Views: 1176
Reputation: 6533
public static Bitmap getBitmapFromView(View view) {
// Define a bitmap with the same size as the view
Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(),
view.getHeight(), Bitmap.Config.ARGB_8888);
// Bind a canvas to it
Canvas canvas = new Canvas(returnedBitmap);
// Get the view's background
Drawable bgDrawable = view.getBackground();
if (bgDrawable != null)
// has background drawable, then draw it on the canvas
bgDrawable.draw(canvas);
else
// does not have background drawable, then draw white background on
// the canvas
canvas.drawColor(Color.WHITE);
// draw the view on the canvas
view.draw(canvas);
// return the bitmap
return returnedBitmap;
}
private String SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/test");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".png";
File file = new File(myDir, fname);
if (file.exists())
file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
And for sharing
Bitmap b = getBitmapFromView(root);
String s = SaveImage(b);
Intent sharingIntent = new Intent(
Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(s);
sharingIntent.setType("image/*");
sharingIntent.putExtra(Intent.EXTRA_STREAM,
Uri.fromFile(new File(s)));
sharingIntent.putExtra(Intent.EXTRA_TEXT,
"save to gallery");
startActivity(sharingIntent);
Upvotes: 1