如何创建和保存截图从surfaceview? [英] how to create and save a screenshot from a surfaceview?

查看:980
本文介绍了如何创建和保存截图从surfaceview?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我希望能够捕捉屏幕截图的应用程序

I have an app that I want to be able to capture a screenshot

下面是我的code:

public class Screenshot {

    private final View view;

    /** Create snapshots based on the view and its children. */
    public Screenshot(View root) {
            this.view = root;
    }

    /** Create snapshot handler that captures the root of the whole activity. */
    public Screenshot(Activity activity) {
            final View contentView = activity.findViewById(android.R.id.content);
            this.view = contentView.getRootView();
    }

    /** Take a snapshot of the view. */
    public Bitmap snap() {
            Bitmap bitmap = Bitmap.createBitmap(this.view.getWidth(), this.view.getHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            view.draw(canvas);
            return bitmap;
    }

}

但surfaceView的内容保存为黑色。!

but the contents of the surfaceView is saved as black.!!!

请帮我,谢谢...

推荐答案

我希望你用这个解决方案,它在这里张贴的获取surfaceView在Android的截图

I hope you have used this solution which was posted here Get screenshot of surfaceView in Android

这件事在此说明以SurfaceView 的截图

的SurfaceView的表面是独立于所查看分子被吸收在表面的。因此,捕捉查看内容将不包括SurfaceView .........

The SurfaceView's surface is independent of the surface on which View elements are drawn. So capturing the View contents won't include the SurfaceView.........

我希望这<一href="http://stackoverflow.com/questions/18289544/taking-screenshot-programmatically-doesnt-capture-the-contents-of-surfaceview">Taking截图编程犯规捕获surfaceVIew code中的内容可以帮助你更

I hope this Taking screenshot programmatically doesnt capture the contents of surfaceVIew code can help you out more

公共类Cam_View扩展活动实现SurfaceHolder.Callback {

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;
}

}

试试这也

public static Bitmap overlay(Bitmap bmp1,Bitmap bmp2) {
            Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(),      bmp1.getConfig());
            Canvas canvas = new Canvas(bmOverlay);
            canvas.drawBitmap(bmp1, 0,0, null);

            canvas.drawBitmap(bmp2, 0, 0, null);
            Log.i("bmOverlay.......",""+bmOverlay);
            bmp3=bmOverlay;
            return bmOverlay;
        }

           private void getScreen() {
            Toast.makeText(BookType1.this, "saved", Toast.LENGTH_SHORT).show();
              File myDir=new File("/sdcard/saved_images");
                myDir.mkdirs();
                Random generator = new Random();
                int n = 10000;
                n = generator.nextInt(n);
                String fname = "Image-"+ n +".png";
                File file = new File (myDir, fname);


            try 
            {

                FileOutputStream ostream = new FileOutputStream(file);
                bmp3.compress(CompressFormat.PNG, 100, ostream);


                ostream.close();
            } 
            catch (Exception e) 
            {
                e.printStackTrace();
            }
        }

,你也可以通过这些引用它给你更多的想法

and you can also go through these references which gives you more idea

<一个href="http://stackoverflow.com/questions/11505093/how-to-capture-screenshot-of-surfaceview-with-background">How捕捉surfaceview背景的截图

<一个href="http://stackoverflow.com/questions/12724237/taking-screen-shot-of-a-surfaceview-in-android">Taking截屏SurfaceView的机器人

<一个href="http://stackoverflow.com/questions/14620055/how-to-take-a-screenshot-of-androids-surface-view">How充分利用Android的表面观截图?

<一个href="http://stackoverflow.com/questions/2661536/how-to-programatically-take-a-screenshot-on-android">How以编程方式采取截图在Android?

这篇关于如何创建和保存截图从surfaceview?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆