当前活动截图并将图像保存到android中的sdcard

时间:2014-07-14 06:41:18

标签: android screenshot sd-card

嗨在我的应用程序中,我在android中创建一个应用程序,我必须截取当前活动的屏幕截图并将其保存到SD卡中。

为此我使用一个名为下载的菜单按钮,如果我点击下载我想将当前活动保存到SD卡。

现在我的问题是它保存到SD卡但屏幕截图变成了一半。我想下载整个屏幕并将其保存到sdcard.how下载完整的活动。

任何人都可以帮我解决这个问题。

notify_image

public class notify_image extends Activity {



        ImageView imageView;

        Activity av=notify_image.this;
        Bitmap b;
        String strFileName;

        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.notify_image);


            imageView = (ImageView) findViewById(R.id.iv_imageview);
            Intent in = getIntent();

            String title = in.getStringExtra("TAG_TITLE");
            String url = in.getStringExtra("TAG_URL");
            String name = in.getStringExtra("TAG_NAME");
            String place = in.getStringExtra("TAG_PLACE");
            String date = in.getStringExtra("TAG_DATE");
            final String URL =url;
            TextView stitle = (TextView) findViewById(R.id.tv_title);
            TextView sname = (TextView) findViewById(R.id.tv_name);
            TextView splace = (TextView) findViewById(R.id.tv_place);
            TextView sdate = (TextView) findViewById(R.id.tv_date);  

            // displaying selected product name
            stitle.setText(title);
            sname.setText(name);
            splace.setText(place);
            sdate.setText(date);






            // Create an object for subclass of AsyncTask
            GetXMLTask task = new GetXMLTask();
            // Execute the task
            task.execute(new String[] { URL });
        }


        //creating button
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.downloads, menu);
            return true;
        }

        //button on click function
        public boolean onOptionsItemSelected(MenuItem item) {    
            switch (item.getItemId()) {    
                case R.id.downloads:
                    /*Bitmap bitmap = takeScreenshot();
                       saveBitmap(bitmap);
                    */
                    //captureScreen(v); 
                    try{
                        Bitmap bitmap = takeScreenShot(av); // av is instance of hello
                        savePic(bitmap, strFileName);
                        }
                    catch (Exception e) {
               System.out.println(e);
            }

         return true;

            default:
                return super.onOptionsItemSelected(item);
        }



        }
       private static Bitmap takeScreenShot(Activity activity) {
            View view = activity.getWindow().getDecorView();
            view.setDrawingCacheEnabled(true);
            view.buildDrawingCache();
            Bitmap b1 = view.getDrawingCache();
            Rect frame = new Rect();
            activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
            int statusBarHeight = frame.top;
            int width = activity.getWindowManager().getDefaultDisplay().getWidth();
            int height = activity.getWindowManager().getDefaultDisplay()
            .getHeight();
            // Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
            Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
             - statusBarHeight);
            view.destroyDrawingCache();
            return b;
                }
        /*public void takeScreen() {
            Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
            String mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".jpeg";
            File imageFile = new File(mPath);
            OutputStream fout = null;
            try {
                fout = new FileOutputStream(imageFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
                fout.flush();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                fout.close();
            }
        }*/
        @SuppressWarnings("unused")
       private static void savePic(Bitmap bitmap, String strFileName) {
            //File strFileName1 = new File(Environment.getExternalStorageDirectory() + "/screenshottt.png");
            FileOutputStream fos = null;
            try {
            fos = new FileOutputStream("mnt/sdcard/print.png");
            if (null != fos) {
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
            System.out.println("b is:"+bitmap);
            fos.flush();
            fos.close();
            }
            } catch (FileNotFoundException e) {
            e.printStackTrace();
            } catch (IOException e) {
            e.printStackTrace();
            }
            }

            public static void shoot(Activity a,String b) {
            //savePic(takeScreenShot(a), "sdcard/xx.png");
            savePic(takeScreenShot(a), b);
            }
      /*public Bitmap takeScreenshot() {
               View rootView = findViewById(android.R.id.content).getRootView();
               rootView.setDrawingCacheEnabled(true);
               return rootView.getDrawingCache();
            }*/
        /*public Bitmap captureScreen(View v)
        {
        Bitmap bitmap = null;

        try {
        if(v!=null)
        {
        int width = v.getWidth();
        int height = v.getHeight();

        Bitmap screenshot = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
        v.draw(new Canvas(screenshot));
        }
        } catch (Exception e)
        {
        Log.d("captureScreen", "Failed");
        }

        return bitmap;
        }
        */
       /* public Bitmap screenShot(View view) {
            Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
                    view.getHeight(), Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            view.draw(canvas);
            return bitmap;
        }*/
       /* public void saveBitmap(Bitmap bitmap) {
            File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
            FileOutputStream fos;
            try {
                fos = new FileOutputStream(imagePath);
                bitmap.compress(CompressFormat.JPEG, 100, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                Log.e("GREC", e.getMessage(), e);
            } catch (IOException e) {
                Log.e("GREC", e.getMessage(), e);
            }
        }*/

        //image url convert to bitmap

        private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
            @Override
            protected Bitmap doInBackground(String... urls) {
                Bitmap map = null;
                for (String url : urls) {
                    map = downloadImage(url);
                }
                return map;
            }

            // Sets the Bitmap returned by doInBackground
            @Override
            protected void onPostExecute(Bitmap result) {
                imageView.setImageBitmap(result);
            }

            // Creates Bitmap from InputStream and returns it
            private Bitmap downloadImage(String url) {
                Bitmap bitmap = null;
                InputStream stream = null;
                BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                bmOptions.inSampleSize = 1;

                try {
                    stream = getHttpConnection(url);
                    bitmap = BitmapFactory.
                            decodeStream(stream, null, bmOptions);
                    stream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                return bitmap;
            }

            // Makes HttpURLConnection and returns InputStream
            private InputStream getHttpConnection(String urlString)
                    throws IOException {
                InputStream stream = null;
                URL url = new URL(urlString);
                URLConnection connection = url.openConnection();

                try {
                    HttpURLConnection httpConnection = (HttpURLConnection) connection;
                    httpConnection.setRequestMethod("GET");
                    httpConnection.connect();

                    if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                        stream = httpConnection.getInputStream();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                return stream;
            }
        }
    }

提前致谢。

新的更新代码

public class notify_image extends Activity {



    ImageView imageView;

    Activity av=notify_image.this;
    Bitmap b;
    String strFileName;
    Button download;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.notify_image);


        imageView = (ImageView) findViewById(R.id.iv_imageview);
        download = (Button) findViewById(R.id.button1);
        download();

        Intent in = getIntent();

        String title = in.getStringExtra("TAG_TITLE");
        String url = in.getStringExtra("TAG_URL");
        String name = in.getStringExtra("TAG_NAME");
        String place = in.getStringExtra("TAG_PLACE");
        String date = in.getStringExtra("TAG_DATE");
        final String URL =url;
        TextView stitle = (TextView) findViewById(R.id.tv_title);
        TextView sname = (TextView) findViewById(R.id.tv_name);
        TextView splace = (TextView) findViewById(R.id.tv_place);
        TextView sdate = (TextView) findViewById(R.id.tv_date);  

        // displaying selected product name
        stitle.setText(title);
        sname.setText(name);
        splace.setText(place);
        sdate.setText(date);






        // Create an object for subclass of AsyncTask
        GetXMLTask task = new GetXMLTask();
        // Execute the task
        task.execute(new String[] { URL });
    }


    //creating button
   /* public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.downloads, menu);
        return true;
    }
*/
    //button on click function
   /* public boolean onOptionsItemSelected(MenuItem item) {    
        switch (item.getItemId()) {    
            case R.id.downloads:
                Bitmap bitmap = takeScreenshot();
                   saveBitmap(bitmap);

                //captureScreen(v); 
                try{
                    Bitmap bitmap = takeScreenShot(av); // av is instance of hello
                    savePic(bitmap, strFileName);
                    }
                catch (Exception e) {
           System.out.println(e);
        }

     return true;

        default:
            return super.onOptionsItemSelected(item);
    }



    }*/

   private void download() {
        // TODO Auto-generated method stub

            // TODO Auto-generated method stub
            /*Intent nextScreen = new Intent(getApplicationContext(), KnowYourLeader.class);
            startActivity(nextScreen);*/
       try{
           Bitmap bitmap = takeScreenShot(av); // av is instance of hello
           savePic(bitmap, strFileName);
           }
       catch (Exception e) {
  System.out.println(e);
}

        }





private static Bitmap takeScreenShot(Activity activity) {
        View view = activity.getWindow().getDecorView();
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        Bitmap b1 = view.getDrawingCache();
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        int statusBarHeight = frame.top;
        int width = activity.getWindowManager().getDefaultDisplay().getWidth();
        int height = activity.getWindowManager().getDefaultDisplay()
        .getHeight();
        // Bitmap b = Bitmap.createBitmap(b1, 0, 25, 320, 455);
        Bitmap b = Bitmap.createBitmap(b1, 0, statusBarHeight, width, height
         - statusBarHeight);
        view.destroyDrawingCache();
        return b;
            }
    /*public void takeScreen() {
        Bitmap bitmap = ImageUtils.loadBitmapFromView(this, view); //get Bitmap from the view
        String mPath = Environment.getExternalStorageDirectory() + File.separator + "screen_" + System.currentTimeMillis() + ".jpeg";
        File imageFile = new File(mPath);
        OutputStream fout = null;
        try {
            fout = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
            fout.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            fout.close();
        }
    }*/
    @SuppressWarnings("unused")
   private static void savePic(Bitmap bitmap, String strFileName) {
        //File strFileName1 = new File(Environment.getExternalStorageDirectory() + "/screenshottt.png");
        FileOutputStream fos = null;
        try {
        fos = new FileOutputStream("mnt/sdcard/print.png");
        if (null != fos) {
        bitmap.compress(Bitmap.CompressFormat.PNG, 90, fos);
        System.out.println("b is:"+bitmap);
        fos.flush();
        fos.close();
        }
        } catch (FileNotFoundException e) {
        e.printStackTrace();
        } catch (IOException e) {
        e.printStackTrace();
        }
        }

        public static void shoot(Activity a,String b) {
        //savePic(takeScreenShot(a), "sdcard/xx.png");
        savePic(takeScreenShot(a), b);
        }
  /*public Bitmap takeScreenshot() {
           View rootView = findViewById(android.R.id.content).getRootView();
           rootView.setDrawingCacheEnabled(true);
           return rootView.getDrawingCache();
        }*/
    /*public Bitmap captureScreen(View v)
    {
    Bitmap bitmap = null;

    try {
    if(v!=null)
    {
    int width = v.getWidth();
    int height = v.getHeight();

    Bitmap screenshot = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_4444);
    v.draw(new Canvas(screenshot));
    }
    } catch (Exception e)
    {
    Log.d("captureScreen", "Failed");
    }

    return bitmap;
    }
    */
   /* public Bitmap screenShot(View view) {
        Bitmap bitmap = Bitmap.createBitmap(view.getWidth(),
                view.getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
        return bitmap;
    }*/
   /* public void saveBitmap(Bitmap bitmap) {
        File imagePath = new File(Environment.getExternalStorageDirectory() + "/screenshot.png");
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(imagePath);
            bitmap.compress(CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            Log.e("GREC", e.getMessage(), e);
        } catch (IOException e) {
            Log.e("GREC", e.getMessage(), e);
        }
    }*/

    //image url convert to bitmap

    private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
        @Override
        protected Bitmap doInBackground(String... urls) {
            Bitmap map = null;
            for (String url : urls) {
                map = downloadImage(url);
            }
            return map;
        }

        // Sets the Bitmap returned by doInBackground
        @Override
        protected void onPostExecute(Bitmap result) {
            imageView.setImageBitmap(result);
        }

        // Creates Bitmap from InputStream and returns it
        private Bitmap downloadImage(String url) {
            Bitmap bitmap = null;
            InputStream stream = null;
            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            bmOptions.inSampleSize = 1;

            try {
                stream = getHttpConnection(url);
                bitmap = BitmapFactory.
                        decodeStream(stream, null, bmOptions);
                stream.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            return bitmap;
        }

        // Makes HttpURLConnection and returns InputStream
        private InputStream getHttpConnection(String urlString)
                throws IOException {
            InputStream stream = null;
            URL url = new URL(urlString);
            URLConnection connection = url.openConnection();

            try {
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.setRequestMethod("GET");
                httpConnection.connect();

                if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    stream = httpConnection.getInputStream();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            return stream;
        }
    }
}

2 个答案:

答案 0 :(得分:0)

这是允许我的屏幕截图存储在SD卡上并随后用于您需要的代码,您可以使用以下代码实现:

// image naming and path  to include sd card  appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" +  ACCUWX.IMAGE_APPEND;   

// create bitmap screen capture
Bitmap bitmap;
View v1 = view.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);

OutputStream fout = null;
imageFile = new File(mPath);

try {
    fout = new FileOutputStream(imageFile);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
    fout.flush();
    fout.close();

} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}  

然后,当你需要访问时使用这样的东西:     Uri uri = Uri.fromFile(new File(mPath));

答案 1 :(得分:0)

尝试以下代码捕获整个屏幕并保存为位图。:

View v = view.getRootView();
v.setDrawingCacheEnabled(true);
Bitmap b = v.getDrawingCache();
String extr = Environment.getExternalStorageDirectory().toString();
File myPath = new File(extr, "print.jpg");
FileOutputStream fos = null;
try {
    fos = new FileOutputStream(myPath);
    b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    fos.flush();
    fos.close();
    MediaStore.Images.Media.insertImage( getContentResolver(), b, 
                                         "Screen", "screen");
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

希望这会对你有所帮助。