将文件保存在SD卡上,写入文件大小为0

时间:2012-03-10 03:21:06

标签: android image file sd-card

我在SD卡上保存图像时遇到问题。我可以在SD卡上看到该文件,但文件为空(大小为0)。我试着把它保存在手机内存上,它运行正常。这是我的代码。

    Imagewritter {

       public static boolean writeAsJPG(Context context, Bitmap bitmap,
    String filename) {
       filename = filename + ".jpg";
       File path = Environment.getExternalStorageDirectory();

    File f = new File(path, filename);
    FileOutputStream fos = null;

    try {
        fos = new FileOutputStream(f);
    } catch (FileNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    try {
        fos = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.d(TAG, "file not found");
        return false;
    }

    bitmap.compress(CompressFormat.JPEG, quality, fos);
    try {
        fos.flush();
        fos.close();
    } catch (IOException e) {
        Log.d(TAG, "error closing");
        e.printStackTrace();
    }
    }

这是位图来自的代码。

    DrawingView = (drawing) findViewById(R.id.drawing_view);
    drawingBitmap = (Bitmap) DrawingView.getBitmap();
    String idName = timeStampText;
    //save Image as JPG
    ImageWritter.writeAsJPG(getApplicationContext(), drawingBitmap, idName);

3 个答案:

答案 0 :(得分:2)

我认为你必须在清单文件中添加这些权限

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

答案 1 :(得分:0)

以字节数组获取图像&amp;检查那个字节数组的大小..我认为你得到0大小的字节数组.....

答案 2 :(得分:0)

这里唯一的问题是我有两行用于编写文件。使用FileOutputStream和OpenFileOutput。只需删除这些行就可以了。

    try {
        fos = context.openFileOutput(filename, Context.MODE_WORLD_READABLE);
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        Log.d(TAG, "file not found");
        return false;
    }