How to attach image from drawable to gmail?

后端 未结 4 1114
醉酒成梦
醉酒成梦 2020-11-28 16:49

I am trying to attach image from my gridview to gmail or facebook,but whenever i tried to attach my app got crash,and i am getting following error with nullpointer exceptio

4条回答
  •  遥遥无期
    2020-11-28 17:23

    Here is the working code which you need:

    Firstly save image from Drawable to SD Card here is the code:

    try{
    
    Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.bubble_green);
    
                //replace "R.drawable.bubble_green" with the image resource you want to share from drawable 
    
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                largeIcon.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
    
                // you can create a new file name "test.jpg" in sdcard folder.
                File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.jpg");
    
                f.createNewFile();
    
                // write the bytes in file
                FileOutputStream fo = new FileOutputStream(f);
                fo.write(bytes.toByteArray());
    
                // remember close de FileOutput
                fo.close();
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    

    Then get the saved image from SD card and attach in the email intent like this:

            Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
            shareIntent.setType("image/jpeg");
    
            shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Hi"); //set your subject
            shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, "How are you"); //set your message
    
            String imagePath = Environment.getExternalStorageDirectory() + File.separator + "test.jpg";
    
            File imageFileToShare = new File(imagePath);
    
            Uri uri = Uri.fromFile(imageFileToShare);
    
            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
    
            startActivity(Intent.createChooser(shareIntent, "Share Image"));
    

提交回复
热议问题