Saving canvas to bitmap on Android

前端 未结 5 1495
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-05 13:24

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.80K

相关标签:
5条回答
  • 2021-01-05 13:52

    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

    0 讨论(0)
  • 2021-01-05 13:58

    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;
      }
    
    0 讨论(0)
  • 2021-01-05 14:03

    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.

    0 讨论(0)
  • 2021-01-05 14:16

    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);
    
    0 讨论(0)
  • 2021-01-05 14:17

    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.

    0 讨论(0)
提交回复
热议问题