简体   繁体   中英

Black Image when taking screenshot

I want to capture my Android screen using a bitmap, and then transform it into an image. The methods should be static.

This is my code in which I register a button click, and when it is clicked "takeScrernshot" captures TextureView and transforms it into Bitmap, and then saves it into a File .

public class MainActivity extends AppCompatActivity {

    //  View rootView = getWindow().getDecorView().getRootView();
    private static TextureView textureView;
    Button button;
    SurfaceView mPreview;
    private SurfaceHolder holder;

    private static File screenshotFile;

    private static float videoWidth = 1080.0f;
    private static float videoHeight = 1920.0f;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textureView = (TextureView) findViewById(R.id.textureView);
        button = (Button) findViewById(R.id.button);

       // mPreview = (SurfaceView) findViewById(R.id.surface);
//        holder = mPreview.getHolder();
       // holder.setFormat(PixelFormat.RGBX_8888);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // takeScreenShot();
                takeScreenshotVideoPlaying();
            }
        });
    }



    public static Bitmap takeScreenshotVideoPlaying() {
        Log.d("", "takeScreenshotVideoPlaying() in VideoPlayerActivity running!");

        Bitmap bitmap = null;
        int tries = 100;
        for (int i = 1; i < tries; i++) {
            if (textureView.isAvailable()) {

                float bitmapScale = 4.0f;
                float bitmapWidth = videoWidth / bitmapScale;
                float bitmapHeight = videoHeight / bitmapScale;
                bitmap = textureView.getBitmap((int) bitmapWidth, (int) bitmapHeight);
                if (bitmap != null) {
                    Log.d("", "screenshot taken");
                    break;
                }
            }
        }
        saveScreenshot(bitmap);
        return bitmap;
    }


    private static void saveScreenshot(Bitmap bitmap) {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();

        Date now = new Date();
        android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);


        String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
        // see if this helps the uploading to GCS

        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);

        screenshotFile = new File(mPath);
        try {
            if (screenshotFile.exists()) {
                screenshotFile.delete();
            }
            if (screenshotFile.createNewFile()) {
                FileOutputStream fo = new FileOutputStream(screenshotFile);
                fo.write(bytes.toByteArray());
                fo.close();
                Log.d("Saved", "saveScreenshot: ");

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}



**and this is how layout looks like:**

I have a texture view, which I will need to register taps, and button to create a screenshot (just for testing) After transforming bitmap into File - image is black

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#534783"
    tools:context="com.maks.testscreenshots.MainActivity">


    <TextureView
        android:id="@+id/textureView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"/>

    <!--<SurfaceView-->
        <!--android:id="@+id/surface"-->
        <!--android:layout_width="wrap_content"-->
        <!--android:layout_height="wrap_content"-->
        <!--android:layout_gravity="center" />-->

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:text="Button"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginTop="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginBottom="8dp"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_constraintLeft_toLeftOf="parent" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:background="@color/colorAccent"
        android:textSize="100sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:id="@+id/textView" />

</android.support.constraint.ConstraintLayout>

The problem was, that I had been trying to screenshot textureView , which rendered Video, so when I tried to getBitmap of screen, I obtained black screen, due to the image changing every time. To capture video I used 2 different methods: -For rooted devices I captured the whole screen, with mouse cursor or anything else on the screen:

 private static Bitmap takeScreenshot() {
        Bitmap screen;
        Bitmap resizedBitmap = null;
        try {
            Process sh = Runtime.getRuntime().exec("su", null, null);

            OutputStream os = sh.getOutputStream();
            Log.d("SCREENSHOT ", "PATH: " + ActFileUtil.getPathToScreenshotDirOnDevice());
            os.write(("/system/bin/screencap -p " + ActFileUtil.getPathToScreenshotDirOnDevice()).getBytes("ASCII"));
            os.flush();
            os.close();
            sh.waitFor();
            Log.d(TAG, "procScreenshot: SCREENSHOT TAKEN");
            screen = BitmapFactory.decodeFile(ActFileUtil.getPathToScreenshotDirOnDevice());
            if(screen != null) {
                resizedBitmap = Bitmap.createScaledBitmap(screen, screen.getWidth() / 4, screen.getHeight() / 4, true);
            }


        } catch (IOException | NullPointerException | InterruptedException e) {
            e.printStackTrace();
        }

        return resizedBitmap;
    }
  • For devices without root, I just used built-in method of MediaPlayer :

    Bitmap bm = mMediaPlayer.getCurrentFrame();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM