How to attach image view as an email attachment?

2019-07-16 17:36发布

I am generating pie chart on image view, I want to send it via email.

How to convert image view's image to email attachment, as its not available in resources?

3条回答
Bombasti
2楼-- · 2019-07-16 18:21

It sounds to me like a lot of extra work is going on here. If you have the ImageView available at run-time, we'll call it mImageView, then you could do something like this:

Drawable mDrawable = mImageView.getDrawable();
Bitmap mBitmap = ((BitmapDrawable)mDrawable).getBitmap();

Now you have a Bitmap image that you can append to an email as an attachment. I haven't prototyped it to make 100% sure this will do exactly what you're looking for, but it seems a lot more elegant than saving it to the SD card just so you can stream it back to a Bitmap and attach it to an email.

Let me know if that doesn't work and I'll try to prototype out something

Thanks, David

查看更多
Explosion°爆炸
3楼-- · 2019-07-16 18:34

The easiest and most Android-friendly way would be to use the ACTION_SEND Intent. The code would look something like this:

    path = "/path/to/image/"
    Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    Uri screenshotUri = Uri.parse(path);

    sharingIntent.setType("image/png");
    sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
    startActivity(Intent.createChooser(sharingIntent, "Share image using"));
查看更多
叼着烟拽天下
4楼-- · 2019-07-16 18:38

Call getDrawingCache() on your image view. This returns the cache bitmap of the view. Read documentation here.

Save the bitmap as PNG, create a mail and attach and send.

Bitmap bmp = imgView.getDrawingCache();
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_WORLD_READABLE);
bmp.compress(Bitmap.CompressFormat.PNG, 0, fos);
fos.close();

/* Create a Action_SEND intent and attach the FILENAME image to the mail. */
...
intent.putExtra(Intent.EXTRA_STREAM, FILENAME); // FILENAME is URI
...
startActivity(....);
查看更多
登录 后发表回答