0

Hi StackOverflow community,

in my application I'd like to have a button which allows the user to capture the current view.

For that reason, I've written the following method (oriented towards: Android save view to jpg or png ):

private LinearLayout container; 

public void createImageOfCurrentView(View v) {
    if (isExternalStoragePresent()) {
        container = (LinearLayout) findViewById(R.id.container);
        container.setDrawingCacheEnabled(true);
        Bitmap b = container.getDrawingCache();

        File dir = new File(Environment.getExternalStorageDirectory().getPath()
          + "/" + getPackageName() + "/");
        dir.mkdirs();

        File file = new File(dir, "image.jpg");
        FileOutputStream fos;

        try {
            fos = new FileOutputStream(file);
            b.compress(CompressFormat.JPEG, 95, fos); // NullPointerException!
            Toast.makeText(this, "The current view has been succesfully saved "
              + "as image.", Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e) {
            Toast.makeText(this, "Unfortunatly an error occured and this "
              + "action failed.", Toast.LENGTH_SHORT).show();
        }
    } else {
        Toast.makeText(this, "Bacause of lacking access to the storage "
          + "of this device, the current view couldn't be saved as an image.",
          Toast.LENGTH_LONG).show();
    }
}

The problem is according to LogCat that there occured a NullPointerException when trying to create the jpeg. So probably the method container.getDrawingCache() is not working. On the phone the file is generated. However with the size of 0 bytes and no visible image. I would appreciate any suggestions what I have to do in order to make it work as I want.

Community
  • 1
  • 1
user1335772
  • 277
  • 1
  • 3
  • 10
  • make sure **b** is not null.. – ngesh Apr 16 '12 at 08:15
  • What do you intent with this line? `container.findViewById(R.id.container);` I'm not familiar with using `findviewbyid` like this, but the common questions (like "is `R.id.container` in the current set view?) probably apply? – Nanne Apr 16 '12 at 08:16

2 Answers2

0

Try it -

public static Bitmap convertViewToBitmap(View view) {
   Bitmap result = null;

   try {
      result = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.RGB_565);
      view.draw(new Canvas(result));
   }catch(Exception e) {}    
   return result;
}
Suvam Roy
  • 1,282
  • 2
  • 11
  • 21
0

Try it -

view.setDrawingCacheEnabled(true);
Bitmap = bm = Bitmap.createBitmap(view.getDrawingCache());
view.setDrawingCacheEnabled(false);
Suvam Roy
  • 1,282
  • 2
  • 11
  • 21