以编程方式截取屏幕截图不会捕获 surfaceVIew 的内容

2024-04-17

我有一个应用程序,我希望能够捕获屏幕截图。布局的背景是一个 SurfaceView,显示来自后置摄像头的视频。下面的代码可以截图,但是surfaceView的内容保存为黑色。这是代码:

btn.setOnClickListener(new OnClickListener()
{

public void onClick(View v)
{
    Random num = new Random();
    int nu=num.nextInt(1000);
    Bitmap bmp;
    CamView.setDrawingCacheEnabled(true); 
    CamView.buildDrawingCache(true);
    Bitmap bmp2 = Bitmap.createBitmap(CamView.getDrawingCache()); //Screenshot of the layout
    CamView.setDrawingCacheEnabled(false);

    SurView.setDrawingCacheEnabled(true); 
    SurView.buildDrawingCache(true);
    Bitmap bmp1 = Bitmap.createBitmap(SurView.getDrawingCache()); //Screenshot of the surfaceView
    SurView.setDrawingCacheEnabled(false);

    Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(),bmp1.getConfig());
    Canvas canvas = new Canvas(bmOverlay); //Overlaying the 2 bitmaps
    canvas.drawBitmap(bmp1, 0,0, null);
    canvas.drawBitmap(bmp2, 0,0, null);
    bmp=bmOverlay;

    //saving the file
    ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    bmp.compress(CompressFormat.JPEG, 100, bos); 
    byte[] bitmapdata = bos.toByteArray();
    ByteArrayInputStream fis = new ByteArrayInputStream(bitmapdata);

    String picId=String.valueOf(nu);
    String myfile="Ghost"+picId+".jpeg";

    File dir_image = new  File(Environment.getExternalStorageDirectory()+
            File.separator+"Ultimate Entity Detector");
    dir_image.mkdirs();

    try {
        File tmpFile = new File(dir_image,myfile); 
        FileOutputStream fos = new FileOutputStream(tmpFile);

         byte[] buf = new byte[1024];
            int len;
            while ((len = fis.read(buf)) > 0) {
                fos.write(buf, 0, len);
            }
                fis.close();
                fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
});

我更新了代码。现在我创建 2 个位图,1 个用于布局 xml,1 个用于 SurfaceView,然后将它们叠加到单个位图中。但surfaceView位图仍然是黑色的


我终于解决了这个问题。下面我为那些想知道如何截取布局屏幕截图、无意中从相机中截取图片、surfaceView 内容屏幕截图(某种程度)并将屏幕截图保存在文件夹中的人提供了一些代码:

public class Cam_View extends Activity implements SurfaceHolder.Callback {

    protected static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
    private SurfaceView SurView;
    private SurfaceHolder camHolder;
    private boolean previewRunning;
    final Context context = this;
    public static Camera camera = null;
    private RelativeLayout CamView;
    private Bitmap inputBMP = null, bmp, bmp1;
    private ImageView mImage;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.camera);

        CamView = (RelativeLayout) findViewById(R.id.camview);//RELATIVELAYOUT OR 
                                                              //ANY LAYOUT OF YOUR XML

        SurView = (SurfaceView)findViewById(R.id.sview);//SURFACEVIEW FOR THE PREVIEW 
                                                        //OF THE CAMERA FEED
        camHolder = SurView.getHolder();                           //NEEDED FOR THE PREVIEW
        camHolder.addCallback(this);                               //NEEDED FOR THE PREVIEW
        camHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);//NEEDED FOR THE PREVIEW
        camera_image = (ImageView) findViewById(R.id.camera_image);//NEEDED FOR THE PREVIEW

        Button btn = (Button) findViewById(R.id.button1); //THE BUTTON FOR TAKING PICTURE

        btn.setOnClickListener(new OnClickListener() {    //THE BUTTON CODE
            public void onClick(View v) {
                  camera.takePicture(null, null, mPicture);//TAKING THE PICTURE
                                                         //THE mPicture IS CALLED 
                                                         //WHICH IS THE LAST METHOD(SEE BELOW)
            }
        });
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,//NEEDED FOR THE PREVIEW
        int height) {
        if(previewRunning) {
            camera.stopPreview();
        }
        Camera.Parameters camParams = camera.getParameters();
        Camera.Size size = camParams.getSupportedPreviewSizes().get(0);
        camParams.setPreviewSize(size.width, size.height);
        camera.setParameters(camParams);
        try {
            camera.setPreviewDisplay(holder);
            camera.startPreview();
            previewRunning=true;
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    public void surfaceCreated(SurfaceHolder holder) {                  //NEEDED FOR THE PREVIEW
        try {
            camera=Camera.open();
        } catch(Exception e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
            finish();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {             //NEEDED FOR THE PREVIEW
        camera.stopPreview();
        camera.release();
        camera=null;
    }

    public void TakeScreenshot(){    //THIS METHOD TAKES A SCREENSHOT AND SAVES IT AS .jpg
        Random num = new Random();
        int nu=num.nextInt(1000); //PRODUCING A RANDOM NUMBER FOR FILE NAME
        CamView.setDrawingCacheEnabled(true); //CamView OR THE NAME OF YOUR LAYOUR
        CamView.buildDrawingCache(true);
        Bitmap bmp = Bitmap.createBitmap(CamView.getDrawingCache());
        CamView.setDrawingCacheEnabled(false); // clear drawing cache
        ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
        bmp.compress(CompressFormat.JPEG, 100, bos); 
        byte[] bitmapdata = bos.toByteArray();
        ByteArrayInputStream fis = new ByteArrayInputStream(bitmapdata);

        String picId=String.valueOf(nu);
        String myfile="Ghost"+picId+".jpeg";

        File dir_image = new  File(Environment.getExternalStorageDirectory()+//<---
                        File.separator+"Ultimate Entity Detector");          //<---
        dir_image.mkdirs();                                                  //<---
        //^IN THESE 3 LINES YOU SET THE FOLDER PATH/NAME . HERE I CHOOSE TO SAVE
        //THE FILE IN THE SD CARD IN THE FOLDER "Ultimate Entity Detector"

        try {
            File tmpFile = new File(dir_image,myfile); 
            FileOutputStream fos = new FileOutputStream(tmpFile);

            byte[] buf = new byte[1024];
            int len;
            while ((len = fis.read(buf)) > 0) {
                fos.write(buf, 0, len);
            }
            fis.close();
            fos.close();
            Toast.makeText(getApplicationContext(),
                           "The file is saved at :SD/Ultimate Entity Detector",Toast.LENGTH_LONG).show();
            bmp1 = null;
            camera_image.setImageBitmap(bmp1); //RESETING THE PREVIEW
            camera.startPreview();             //RESETING THE PREVIEW
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private PictureCallback mPicture = new PictureCallback() {   //THIS METHOD AND THE METHOD BELOW
                                 //CONVERT THE CAPTURED IMAGE IN A JPG FILE AND SAVE IT

        @Override
        public void onPictureTaken(byte[] data, Camera camera) {

            File dir_image2 = new  File(Environment.getExternalStorageDirectory()+
                            File.separator+"Ultimate Entity Detector");
            dir_image2.mkdirs();  //AGAIN CHOOSING FOLDER FOR THE PICTURE(WHICH IS LIKE A SURFACEVIEW
                                  //SCREENSHOT)

            File tmpFile = new File(dir_image2,"TempGhost.jpg"); //MAKING A FILE IN THE PATH
                            //dir_image2(SEE RIGHT ABOVE) AND NAMING IT "TempGhost.jpg" OR ANYTHING ELSE
            try { //SAVING
                FileOutputStream fos = new FileOutputStream(tmpFile);
                fos.write(data);
                fos.close();
                //grabImage();
            } catch (FileNotFoundException e) {
                Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
            }

            String path = (Environment.getExternalStorageDirectory()+
                            File.separator+"Ultimate EntityDetector"+
                                                File.separator+"TempGhost.jpg");//<---

            BitmapFactory.Options options = new BitmapFactory.Options();//<---
                options.inPreferredConfig = Bitmap.Config.ARGB_8888;//<---
            bmp1 = BitmapFactory.decodeFile(path, options);//<---     *********(SEE BELOW)
            //THE LINES ABOVE READ THE FILE WE SAVED BEFORE AND CONVERT IT INTO A BitMap
            camera_image.setImageBitmap(bmp1); //SETTING THE BitMap AS IMAGE IN AN IMAGEVIEW(SOMETHING
                                        //LIKE A BACKGROUNG FOR THE LAYOUT)

            tmpFile.delete();
            TakeScreenshot();//CALLING THIS METHOD TO TAKE A SCREENSHOT
            //********* THAT LINE MIGHT CAUSE A CRASH ON SOME PHONES (LIKE XPERIA T)<----(SEE HERE)
            //IF THAT HAPPENDS USE THE LINE "bmp1 =decodeFile(tmpFile);" WITH THE METHOD BELOW

        }
    };

    public Bitmap decodeFile(File f) {  //FUNCTION BY Arshad Parwez
        Bitmap b = null;
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;

            FileInputStream fis = new FileInputStream(f);
            BitmapFactory.decodeStream(fis, null, o);
            fis.close();
            int IMAGE_MAX_SIZE = 1000;
            int scale = 1;
            if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
                scale = (int) Math.pow(
                        2,
                        (int) Math.round(Math.log(IMAGE_MAX_SIZE
                                / (double) Math.max(o.outHeight, o.outWidth))
                                / Math.log(0.5)));
            }

            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            fis = new FileInputStream(f);
            b = BitmapFactory.decodeStream(fis, null, o2);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return b;
    }
}

如果您想拍摄简单的屏幕截图(不需要相机输入),您可以单独使用 TakeScreenshot 方法。

如果你想截取 SurfaceView 的屏幕截图,但无法直接从 SurfaceView 进行截屏,请使用 mPicture,将捕获的图片设置为背景,然后调用 TakeScreenshot 截取屏幕截图。(如上所示)

如果您想使用相机拍照而不有意调用其他相机应用程序,请使用上面代码中的 takePicture 和 mPicture 以及 surfaceView 内容。

如果“按原样”使用,前面的代码的作用是截取布局内容(按钮、图像视图等)的屏幕截图,并将来自相机的图像设置为背景。

下面我还为之前的代码提供了一个基本的布局 xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"   
android:id="@+id/camview">

<SurfaceView
    android:id="@+id/sview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" />

<ImageView
    android:id="@+id/camera_image"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:contentDescription="@string/app_name" />



<Button
    android:id="@+id/button1"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true" />


</RelativeLayout>

不要忘记导入需要导入的内容

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

以编程方式截取屏幕截图不会捕获 surfaceVIew 的内容 的相关文章

  • Android 自定义三角形按钮

    我想制作 2 个对角三角形按钮 如下所示这个问题 https stackoverflow com questions 23315400 android diagonal triangle buttons 我怎样才能实现这个目标 我应该用矩形
  • Android IAB:设备上无法使用计费服务

    我正在尝试在我的应用程序中实现 IAB 每次应用程序启动时 启动都会失败并显示 Problem setting up In app Billing IabResult Billing service unavailable on devic
  • 我们应该首先调用 MobileAds.setRequestConfiguration 还是 MobileAds.initialize?

    这方面没有太多文档 我想知道我们应该先打电话吗 RequestConfiguration conf new RequestConfiguration Builder setMaxAdContentRating MAX AD CONTENT
  • 使用 Jack 时未生成 Dagger 2 组件

    当我启用杰克编译器 https source android com source jack html在Android Studio 2 2中Dagger 2 https google github io dagger 组件未生成 Dagg
  • 如何在 Android Studio 中显示丰富的布局编辑器? [关闭]

    Closed 这个问题是无关 help closed questions 目前不接受答案 如何显示或使用 Android Studio 中讨论的丰富布局编辑器 更多信息我是 Java 新手 刚刚下载了 Android Studio 并创建了
  • Android SQLite 通配符

    我正在尝试使用通配符元素进行查询 以在 SQLite 表中搜索特定变量中任意位置具有元素的条目 public String getCheckoutEntry String title String ISBN Wild card Syntax
  • 如何以编程方式查找USB存储路径?

    我将 USB 存储设备连接到手机并使用 getExternalFilesDirs 查找所有目录 包括 sdcard 和 USB 该功能正确输出了SD卡的路径 但未输出USB路径 有没有办法找到USB的相对路径而不是绝对路径 我已经被这个问题
  • 更改 Android 软键盘示例设计、按钮和背景图像

    我正在通过修改 SDK 中的 android 软键盘示例来构建自定义键盘 我想更改按钮和背景的图像 但我无法弄清楚这些值的存储位置 它们存储在哪里或者我如何更改图像或简单的颜色 在 onClick 方法中 您需要更改按钮的图像 这样 pub
  • 分享图片在 Viber 和 Facebook 中不起作用

    我使用下面的代码来共享图像 但不幸的是它仅适用于Line 不是为了Facebook and Viber Code Intent share new Intent android content Intent ACTION SEND shar
  • 如何在动画结束时开始活动

    这是我的第一个应用程序 我需要在动画结束时开始新的活动 我需要做什么 我的代码 package com lineage goddess import android app Activity import android content I
  • Android JSONObject内部多个JSONObject的解析

    我有一个来自服务器的 JSON 字符串 它看起来像这样 categories 0 term id 247 name Content Curation 1 term id 50 name Content Marketing 2 term id
  • 如何在画布的右上角绘制位图

    我正在尝试绘制位图top right hand corner of the Canvas 到目前为止我已经做了以下事情 100x40 dimensions for the bitmap bitmap BitmapFactory decode
  • 如何在Android中将图像文件转换为pdf文件

    我正在尝试在 Android 应用程序中将图像文件 jpg 转换为 pdf 文件 我用过itextpdf罐子和机器人文本罐 都不适合我 下面是使用时的代码itextpdf Document document new Document Str
  • 检查手机是否可以发送短信

    我已经读过一些相关的问题 但大多数都是针对呼叫 而不是短信 到目前为止我发现的是 TelephonyManager manager TelephonyManager context getSystemService Context TELE
  • 通过 ExoPlayer 进行 Android 流传输

    我正在尝试从MediaPlayer有利于ExoPlayer但我找不到任何更新的演示如何使用它 我认为他们已经删除了FrameworkSampleSource方法 我从 Github 下载了演示 但找不到播放器的实现 我可以找到添加 URL
  • 棒棒糖中的 takePicture 失败

    以下代码正在使用 可在后台拍照 它对于棒棒糖以下的所有版本都工作正常 但在以下版本中给出运行时异常takePicture null null mcall 有任何想法吗 public void takePictures final int d
  • java.lang.IndexOutOfBoundsException:无效索引 7,大小为 7

    我正在尝试实现视图寻呼机 在我的视图寻呼机图像来自服务器 我能够显示和滚动 但当我到达最后一个图像时 它显示错误并且应用程序崩溃 以下是我的代码片段 public class Test Pager extends Activity priv
  • Dagger 2.10 Android 子组件和构建器

    使用新的 2 10 中 dagger android 类 我尝试使用依赖于其他模块的子组件来注入东西 因此 有一个带有这些模块的设置器的构建器 有关的文档https google github io dagger android html
  • 如何在Android应用程序中添加g729编解码器?

    我正在开发一个用于拨打和接听电话的 SIP 应用程序 我想在我的应用程序中添加 G729 编解码器 目前我正在对开源项目进行分析SipDroid http code google com p sipdroid 如果我想让该应用程序支持 G7
  • Google 地图视图无法在模拟器上显示

    您好 我正在尝试在 Android 模拟器中显示地图 但它无法在地图视图中显示谷歌地图 并且也不从 Android 模拟器上的浏览器连接 www google com 那么是否有关于在模拟器上运行互联网的任何设置 谁能帮我解决这个问题 尝试

随机推荐