Sharing Bitmap via Android Intent

后端 未结 8 1578
名媛妹妹
名媛妹妹 2020-12-02 17:35

In my android app, I have a bitmap (say b) and a button. Now when I click on the button, I want to share the bitmap. I am making use of the below code inside my onClic

8条回答
  •  清歌不尽
    2020-12-02 17:48

    After spending a lot of time on this:

    Check if permissions are given. Then:

    Step 1: Create ImageView of the image you want to in the activity and then convert it itno bitmap

    ImageView imageView = findViewById(R.id.image);
    Bitmap bitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
    
    //save the image now:
    saveImage(bitmap);
    //share it
    send();
    

    Step 2: Store the image in internal folder:

    private static void saveImage(Bitmap finalBitmap) {
    
        String root = Environment.getExternalStorageDirectory().getAbsolutePath();
        File myDir = new File(root + "/saved_images");
        Log.i("Directory", "==" + myDir);
        myDir.mkdirs();
    
        String fname = "Image-test" + ".jpg";
        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();
        }
    }
    

    Step 3: Send the saved image:

    public void send() {
        try {
            File myFile = new File("/storage/emulated/0/saved_images/Image-test.jpg");
            MimeTypeMap mime = MimeTypeMap.getSingleton();
            String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
            String type = mime.getMimeTypeFromExtension(ext);
            Intent sharingIntent = new Intent("android.intent.action.SEND");
            sharingIntent.setType(type);
            sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(myFile));
            startActivity(Intent.createChooser(sharingIntent, "Share using"));
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    

    Now after sending you can delete the saved image if you don't want it in your storage. Check other link to do that.

提交回复
热议问题