2013-12-09 87 views
0

到外部存儲器中的圖像我用下面的代碼將圖像寫入到外部存儲在機器人:寫在android系統

File root = android.os.Environment.getExternalStorageDirectory(); 
File dir = new File (root.getAbsolutePath() + "/download"); 
dir.mkdirs(); 
fileName = "image_2.jpeg"; 
File file = new File(dir, fileName); 

try { 
    FileOutputStream outStream = new FileOutputStream(file); 
    Bitmap bitmap = BitmapFactory.decodeFile("android.resource://com.mypackage.com/drawable/image_1"); 
    bitmap.compress(Bitmap.CompressFormat.JPEG, 70, outStream); 
    outStream.flush(); 
    outStream.close(); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

此代碼是從繪製文件夾閱讀image_1.jpg,然後寫它下載文件夾在外部存儲中,使用image_2.jpeg名稱。 (在外部存儲器中創建下載文件夾,並在該文件夾內創建一個名稱爲image_2.jpeg的文件)。 這段代碼將產生一個((強制關閉))。下載文件夾被創建並且image_2.jpeg被創建,但是圖像image_2.jpeg被損壞。

+0

「這個代碼將產生((強制關閉))」 - 使用logcat的檢查Java堆棧跟蹤與您的崩潰相關聯。另外,請不要使用隨機目錄混亂用戶的外部存儲。在'Context'上使用'Environment.getExternalStoragePublicDirectory()'或'getExternalFilesDir()'來獲得文件更明智的地方。 – CommonsWare

回答

1

這些可繪製文件夾中的圖像可以通過BitmapFactory訪問,您可以將位圖保存爲PNG或JPG。

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); 
File sd = Environment.getExternalStorageDirectory(); 
String fileName = "test.png"; 
File dest = new File(sd, fileName); 
try { 
    FileOutputStream out; 
    out = new FileOutputStream(dest); 
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); 
    out.flush(); 
    out.close(); 
} catch (FileNotFoundException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} catch (IOException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

不要忘記添加android.permission.WRITE_EXTERNAL_STORAGE許可。

對於其他類型的圖像,我認爲把它們放入資產文件夾是一種更好的方法。

There is a sample here.

0

我做同樣的事情,與此code.Try此代碼:

String[] sampleImagesName = { "image2" }; 
int[] sampleImages = { R.drawable.image1}; 
File file; 
if (Environment.getExternalStorageState().equals(
    Environment.MEDIA_MOUNTED)) { 
    file = new File(Environment.getExternalStorageDirectory() 
     .getAbsolutePath() + "/download"); 
    if (!file.exists()) { 
     file.mkdirs(); 
     SaveSampleToSD(); 
    } 
} 
private void SaveSampleToSD() { 
     String path = Environment.getExternalStorageDirectory() 
       .getAbsolutePath() + "/download"; 

     for (int i = 0; i < sampleImages.length; i++) { 
      try { 
       File f = new File(path + "/", sampleImagesName[i] + ".jpg"); 
       Bitmap bm = BitmapFactory.decodeResource(getResources(), 
         sampleImages[i]); 
       FileOutputStream out = new FileOutputStream(f); 
       bm.compress(Bitmap.CompressFormat.JPEG, 100, out); 

       out.flush(); 
       out.close(); 

       Log.e("ImageSaved---------", "saved"); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 

     } 
    }