Search code examples
androidandroid-studiosharescreenshot

How to take,crop and share screenshot?


I have a code to take, save then share the screenshot of an Activity. My problem is I want just take the center of the activity so I add this code

private  Bitmap cropBitmap(Bitmap bitmap)  {
            Bitmap bm = Bitmap.createBitmap(bitmap, 10, 10,  500,  500);
            return bm;
        }

But it still the original screenshot, please help me i try much solutions but it seems like I don't know how to apply this solutions because i'm very amateur in coding . So i hope to help me please give me the right solution dependent on my code .Thank you very very much

    @Override
    public void onClick(View v) {
        Bitmap bitmap = takeScreenshot();
        cropBitmap(bitmap);
        saveBitmap(bitmap);
        shareIt();
    }


    public Bitmap takeScreenshot() {
        View v1 = getWindow().getDecorView().getRootView();
        v1.setDrawingCacheEnabled(true);
        Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
        v1.setDrawingCacheEnabled(false);
        return bitmap;
    }

    private  Bitmap cropBitmap(Bitmap bitmap)  {
        Bitmap bm = Bitmap.createBitmap(bitmap, 10, 10,  500,  500);
        return bm;
    }

    private void saveBitmap(Bitmap bitmap) {
        imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png"); ////File imagePath
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(imagePath);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            Log.e("GREC", e.getMessage(), e);
        } catch (IOException e) {
            Log.e("GREC", e.getMessage(), e);
        }


    }

    private void shareIt() {
        Uri myUri = Uri.fromFile(imagePath);
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("image/*");
        sharingIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        String shareBody = "My highest score with screen shot";
        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "My Catch score");
        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
        sharingIntent.putExtra(Intent.EXTRA_STREAM, myUri);

        startActivity(Intent.createChooser(sharingIntent, "Share via"));
    }
});


    displayResults();

Solution

  • Try like this:

    Bitmap bitmap = takeScreenshot();
    Bitmap bitmapCropped = cropBitmap(bitmap);
    saveBitmap(bitmapCropped );