Saving canvas to bitmap on Android

与世无争的帅哥 提交于 2019-11-28 11:31:31

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

You'll have to draw after setting the bitmap to the canvas. Also use a new Canvas object like this:

Canvas canvas = new Canvas(toDisk);
canvas.drawPath(currentPath, pen);
toDisk.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(new File("arun.png")));

I recommend using PNG for saving images of paths.

first create a blank bitmap , then create a canvas with that blank bitmap

 Bitmap.Config conf = Bitmap.Config.ARGB_8888; 
 Bitmap bitmap_object = Bitmap.createBitmap(width, height, conf); 
 Canvas canvas = new Canvas(bitmap_object);

now draw your lines on canvas

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

Now access your bitmap via bitmap_object

you must call canvas.setBitmap(bitmap); before drawing anything on Canvas. After calling canvas.setBitmap(bitmap); draw on Canvas and then save the Bitmap you passed to Canvas.

pradeep

May be

canvas.setBitmap(toDisk);

is not in correct place.

Try this :

toDisk = Bitmap.createBitmap(640,480,Bitmap.Config.ARGB_8888);              
toDisk.compress(Bitmap.CompressFormat.JPEG, 100, new FileOutputStream(new File("arun.jpg")));

canvas.setBitmap(toDisk);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!