保存到SD卡

时间:2012-06-29 15:24:03

标签: android android-sdcard

此代码用于在/Android/data/com.ocr.id/files/IDOCR/Number /

上保存图片
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 个答案:

答案 0 :(得分:0)

尝试在XML文件中添加用户权限!

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
相关问题