2012-06-29 58 views
0

此代碼對/Android/data/com.ocr.id/files/IDOCR/Number/保存圖片保存到SD卡

public static File save(Activity activity, Bitmap bm, String name) { 
    boolean mExternalStorageAvailable = false; 
    boolean mExternalStorageWriteable = false; 
    File number = null; 
    String state = Environment.getExternalStorageState(); 

    if (Environment.MEDIA_MOUNTED.equals(state)) { 
     // We can read and write the media 
     mExternalStorageAvailable = mExternalStorageWriteable = true; 
     OutputStream outStream = null; 

     File externalFilesDir = activity.getExternalFilesDir(null); 
     File outFile = new File(externalFilesDir, "IDOCR" + File.separator 
       + "Numbers"); 

     if (!outFile.exists()) 
      outFile.mkdirs(); 

     String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss") 
       .format(new Date()); 

     number = new File(outFile, timeStamp + "_" + name + ".PNG"); 

     try { 
      outStream = new FileOutputStream(number); 
      bm.compress(Bitmap.CompressFormat.PNG, 100, outStream); 

      outStream.flush(); 
      outStream.close(); 
      outStream = null; 

      bm.recycle(); 
//    bm = null; 

      System.gc(); 

     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

    } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) { 
     // We can only read the media 
     mExternalStorageAvailable = true; 
     mExternalStorageWriteable = false; 
     Toast.makeText(activity, "Your SDcared is read only.", 
       Toast.LENGTH_LONG).show(); 
    } else { 
     // Something else is wrong. It may be one of many other states, but 
     // all we need 
     // to know is we can neither read nor write 
     mExternalStorageAvailable = mExternalStorageWriteable = false; 
     Toast.makeText(activity, "Your SDcared is unmounted.", 
       Toast.LENGTH_LONG).show(); 
    } 
    return number; 
} 

什麼是在代碼拋出一個空指針異常的錯誤這條線

  bm.compress(Bitmap.CompressFormat.PNG, 100, outStream); 

這段代碼之前與我合作,但現在引發了一個例外。

+1

你檢查過,如果傳遞參數,'位圖bm'不爲空。在ebm.compress之前檢查bm&outStream是不是等於null的 –

+0

。並在那裏打印日誌,所以你來了解。 – rajpara

+0

我檢查並不等於空 –

回答

0

嘗試在您的XML文件中添加用戶權限!

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />