Saving canvas to bitmap on Android

user1185687 picture user1185687 · Feb 21, 2013 · Viewed 31.3k times · Source

I'm having some difficulty with regards to placing the contents of a Canvas into a Bitmap. When I attempt to do this, the file gets written with a file size of around 5.80KB but it appears to be completely empty (every pixel is '#000').

The canvas draws a series of interconnected lines that are formed by handwriting. Below is my onDraw for the View. (I'm aware that it's blocking the UI thread / bad practices/ etc.., however I just need to get it working)

Thank you.

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);

        if (IsTouchDown) {

            // Calculate the points
            Path currentPath = new Path();
            boolean IsFirst = true;
            for(Point point : currentPoints){
                if(IsFirst){
                    IsFirst = false;
                        currentPath.moveTo(point.x, point.y);
                    } else {
                        currentPath.lineTo(point.x, point.y);
                    }
                }

            // Draw the path of points
            canvas.drawPath(currentPath, pen);

            // Attempt to make the bitmap and write it to a file.
            Bitmap toDisk = null;
            try {

                // TODO: Get the size of the canvas, replace the 640, 480
                toDisk = Bitmap.createBitmap(640,480,Bitmap.Config.ARGB_8888);
                canvas.setBitmap(toDisk);
                toDisk.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("arun.jpg")));

            } catch (Exception ex) {


            }

        } else {

            // Clear the points
            currentPoints.clear();

        }
    }

Answer

chatlanin picture chatlanin · Nov 26, 2013

I had similar problem and i've got solution. Here full code of a task /don't forget about android.permission.WRITE_EXTERNAL_STORAGE permission in manifest/

  public Bitmap saveSignature(){

      Bitmap  bitmap = Bitmap.createBitmap(this.getWidth(), this.getHeight(), Bitmap.Config.ARGB_8888);
      Canvas canvas = new Canvas(bitmap);
      this.draw(canvas); 

      File file = new File(Environment.getExternalStorageDirectory() + "/sign.png");

      try {
           bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(file));
      } catch (Exception e) {
           e.printStackTrace();
      }

      return bitmap;
  }