1

In my android app i have surface view on which i have canvas and user can draw on canvas.Now i want to capture canvas image and store it to sd card. Below is my code -

 Bitmap bitmap = Bitmap.createBitmap(maxX, maxY, Bitmap.Config.RGB_565);
 canvas.setBitmap(bitmap);
 String mFile = path+"/drawing.png";
        Bitmap bitmap = drawBitmap();
        File file = new File(mFile);
        FileOutputStream fos = new FileOutputStream(file);
        bitmap.compress(CompressFormat.PNG, 100, fos);
        fos.flush();
        fos.close();

code is run but when i open sd card on image path file with name is created but when open image it is black. How to capture image from canvas in android.

Ravi Bhandari
  • 4,682
  • 8
  • 40
  • 68
  • Duplicate of http://stackoverflow.com/questions/25086263/take-screenshot-of-surfaceview/ ? – fadden Dec 09 '14 at 17:33
  • Possible duplicate of [Android Take Screenshot of Surface View Shows Black Screen](https://stackoverflow.com/questions/27817577/android-take-screenshot-of-surface-view-shows-black-screen) – Anjani Mittal Nov 22 '18 at 11:29

1 Answers1

-1

Just pass the your surface view object and file path where you want to store your snapshot. It is working perfectly.

public static void takeScreenshot(View view, String filePath) {
            Bitmap bitmap = getBitmapScreenshot(view);

            File imageFile = new File(filePath);
            imageFile.getParentFile().mkdirs();
            try {
                OutputStream fout = new FileOutputStream(imageFile);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
                fout.flush();
                fout.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

public static Bitmap getBitmapScreenshot(View view) {
        view.measure(MeasureSpec.makeMeasureSpec(view.getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(view.getHeight(), MeasureSpec.EXACTLY));
        view.layout((int)view.getX(), (int)view.getY(), (int)view.getX() + view.getMeasuredWidth(), (int)view.getY() + view.getMeasuredHeight());

        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache(true);
        Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache());
        view.setDrawingCacheEnabled(false);

        return bitmap;
    }
Zeeshan Ahmed
  • 1,179
  • 2
  • 13
  • 30