2012-04-16 75 views
0

嗨StackOverflow的社区时,NullPointerException异常试图保存当前的Android应用程序视图图像

在我的应用我想有一个按钮,允许用户捕获当前视图。

出于这个原因,我已经写了下面的方法(面向: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(); 
    } 
} 

的问题是根据LogCat有试图创建jpeg当发生一个NullPointerException。所以可能的方法container.getDrawingCache()不起作用。在电话上生成文件。但是,大小为0字节并且没有可见的图像。我将不胜感激任何建议,我必须做的才能让它按照我的意愿工作。

+0

确保** ** b不为空.. – ngesh 2012-04-16 08:15:17

+0

你有什么打算用这条线? 'container.findViewById(R.id.container);'我不熟悉像这样使用'findviewbyid',但常见的问题(比如“是当前set视图中的R.id.container')可能适用? – Nanne 2012-04-16 08:16:17

回答

0

试试吧 -

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

这是行得通的。谢谢sooooo! – user1335772 2012-04-16 20:03:23

+0

只有当你有很多内存,FWIW时才能使用。 – 2013-01-21 06:18:48

0

试试吧 -

view.setDrawingCacheEnabled(true); 
Bitmap = bm = Bitmap.createBitmap(view.getDrawingCache()); 
view.setDrawingCacheEnabled(false); 
相关问题