Search code examples
androidandroid-canvassurfaceviewandroid-bitmapsurfaceholder

How can i convert canvas to bitmap for save in sdCard


I use SurfaceView to move two bitmap picture over the screen. I tried this:

...
@Override
protected void onDraw(Canvas canvas) {
  super.onDraw(canvas);

  ...

  canvas.drawBitmap(bitmap,matrix,paint);
  canvas.drawBitmap(bitmap2,matrix,paint);
}
...

How it possible to save canvas into sdCard like this?

public saveCanvasIntoSdCard(Canvas canvas)
{

}

Solution

  • Solution I found:

    public Bitmap getBitmap() {
      Bitmap bmOverlay = Bitmap.createBitmap(bitmap2.getWidth(), bitmap2.getHeight(), bitmap2.getConfig());
      Canvas canvas = new Canvas(bmOverlay);
      canvas.drawBitmap(bitmap, matrix, null);
      canvas.drawBitmap(bitmap2, 0, 0, null);
      return bmOverlay;
    }
    
    public void save(View view){
      String root = Environment.getExternalStorageDirectory().toString();
      File myDir = new File(root + "/dress");    
      myDir.mkdirs();
    
      String fname = "save.jpg";
      File file = new File (myDir, fname);
      if (file.exists ()) file.delete (); 
      try {
      FileOutputStream out = new FileOutputStream(file);
      getBitmap().compress(Bitmap.CompressFormat.JPEG, 100, out);
      out.flush();
      out.close();
    
      } catch (Exception e) {
      e.printStackTrace();
      }
    
    }