2013-04-05 181 views
0

我試圖將捕獲的.bmp文件保存到SD卡。 這裏的代碼片段,其中負責此:Android保存bmp圖像

String root = Environment.getExternalStorageDirectory().toString(); 
    File mFolder = new File(root + "/mFolder"); 

    if (!mFolder.exists()) 
    { 
     mFolder.mkdir(); 
    } 
    String strF = mFolder.getAbsolutePath(); 
    File mSubFolder = new File(strF + "/MyApp-SubFolder"); 

    if (!mSubFolder.exists()) 
    { 
     mSubFolder.mkdir(); 
    } 
    String s = "myfile.png"; 

    File f = new File(mSubFolder.getAbsolutePath(),s); 
    String strMyImagePath = f.getAbsolutePath(); 
    FileOutputStream fos = null; 
    try 
    { 
     fos = new FileOutputStream(f); 
     bmp.compress(Bitmap.CompressFormat.PNG,70, fos); 

     fos.flush(); 
     fos.close(); 
     Log.d("asd", "yeah!"); 
    // MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen"); 
    }catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

但有一個錯誤:

images are invalid and its size are 0kb

我在做什麼錯?

+0

一個String = 「myfile.png」; ?你說該文件是.BMP – Hasham 2013-04-05 13:03:58

+0

試試這個\t文件storagePath =新的文件( \t \t \t \t \t Environment.getExternalStorageDirectory()+ 「/ MyApp的子文件夾中/」); – Hasham 2013-04-05 13:06:02

回答

2

試試這個

private boolean SaveToSD() { 

     String imageName = null; 

     Bitmap sourceBitmap = ((BitmapDrawable) img.getDrawable()).getBitmap(); 

     boolean imageSaved = false; 

     if (sourceBitmap != null && !sourceBitmap.isRecycled()) { 
      File storagePath = new File(
        Environment.getExternalStorageDirectory() + "/iGridu/"); 

      if (!storagePath.exists()) { 
       storagePath.mkdirs(); 
      } 

      int count = storagePath.list().length; 

      Log.i("SaveToSD count", "" + count); 

      imageName = String.valueOf(count + 1) + "_igridu"; 

      FileOutputStream out = null; 
      File imageFile = new File(storagePath, String.format("%s.jpg", 
        imageName)); 
      try { 
       out = new FileOutputStream(imageFile); 
       imageSaved = sourceBitmap.compress(Bitmap.CompressFormat.JPEG, 
         90, out); 
       out.flush(); 
       out.close(); 
      } catch (Exception e) { 
       Log.e("SaveToSD ", "Unable to write the image to gallery" + e); 

      } 

      ContentValues values = new ContentValues(3); 
      values.put(Images.Media.TITLE, imageName); 
      values.put(Images.Media.MIME_TYPE, "image/jpeg"); 
      values.put("_data", imageFile.getAbsolutePath()); 

      getContentResolver().insert(Media.EXTERNAL_CONTENT_URI, values); 
     } 

     return imageSaved; 
    } 
+0

是的,我已將它添加到清單,但它仍然不工作,圖像無效.. – user2249145 2013-04-05 13:16:58

+0

謝謝,但您的代碼無法正常工作。 – user2249145 2013-04-05 13:34:01

+0

現在的問題是什麼? – Hasham 2013-04-08 05:16:53

0

你必須把這個在您的Manifest.xml

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

我已經添加了它,但它沒有改變任何東西。 – user2249145 2013-04-05 13:44:29