2013-10-19 87 views
4

我實現這個代碼有問題Saving and Reading Bitmaps/Images from Internal memory in AndroidAndroid的圖像保存到內部存儲

保存和檢索,我想要的圖像,這裏是我的代碼:

ContextWrapper cw = new ContextWrapper(getApplicationContext()); 
      // path to /data/data/yourapp/app_data/imageDir 
      File directory = cw.getDir("imageDir", Context.MODE_PRIVATE); 
      // Create imageDir 
      File mypath=new File(directory, + name + "profile.jpg"); 

      FileOutputStream fos = null; 
      try {   

       fos = new FileOutputStream(mypath); 

      // Use the compress method on the BitMap object to write image to the OutputStream 
       myBitmap.compress(Bitmap.CompressFormat.PNG, 100, fos); 
       fos.close(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

和檢索(我不不知道我是否做錯了)

@Override 
    protected void onResume() 
    { 
     super.onResume(); 

     try { 
      File f = new File("imageDir/" + rowID, "profile.jpg"); 
     Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f)); 
     image = (ImageView) findViewById(R.id.imageView2); 
     image.setImageBitmap(b); 

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

並沒有發生什麼,所以我應該怎麼改?

+2

請發表您的Logcat與問題。 –

回答

1

請注意,您在imageDir目錄下保存的截齒name + profile.jpg和你試圖檢索爲profile.jpgimageDir/[rowID]目錄檢查。

+0

name和rowId包含相同的值,它只是cuz有不同的類,但是謝謝 – user2580401

14

保存您的位圖的SD卡使用下面的代碼

店鋪形象

private void storeImage(Bitmap image) { 
    File pictureFile = getOutputMediaFile(); 
    if (pictureFile == null) { 
     Log.d(TAG, 
       "Error creating media file, check storage permissions: ");// e.getMessage()); 
     return; 
    } 
    try { 
     FileOutputStream fos = new FileOutputStream(pictureFile); 
     image.compress(Bitmap.CompressFormat.PNG, 90, fos); 
     fos.close(); 
    } catch (FileNotFoundException e) { 
     Log.d(TAG, "File not found: " + e.getMessage()); 
    } catch (IOException e) { 
     Log.d(TAG, "Error accessing file: " + e.getMessage()); 
    } 
} 

得到我認爲Faibo的答案應該被接受的圖像存儲

/** Create a File for saving an image or video */ 
private File getOutputMediaFile(){ 
    // To be safe, you should check that the SDCard is mounted 
    // using Environment.getExternalStorageState() before doing this. 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory() 
      + "/Android/data/" 
      + getApplicationContext().getPackageName() 
      + "/Files"); 

    // This location works best if you want the created images to be shared 
    // between applications and persist after your app has been uninstalled. 

    // Create the storage directory if it does not exist 
    if (! mediaStorageDir.exists()){ 
     if (! mediaStorageDir.mkdirs()){ 
      return null; 
     } 
    } 
    // Create a media file name 
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date()); 
    File mediaFile; 
     String mImageName="MI_"+ timeStamp +".jpg"; 
     mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName); 
    return mediaFile; 
} 
+0

以及如何從另一個類檢索(位圖)它來設置它:image =(ImageView)findViewById(R。 id.imageView2); image.setImageBitmap(...); – user2580401

+0

這個答案中的代碼已經從android開發者直接複製和粘貼,[你可能會發現更有用的答案。](http://developer.android.com/guide/topics/media/camera.html#saving-media ) – Masterfool

+1

不正確的答案... qtn關於內部存儲..關於外部存儲的答案.. –

2

路徑,如該代碼示例是正確的,寫得很好,應該解決您的具體問題,沒有困難。

如果他的解決方案不能滿足您的需求,我想建議一種替代方法。

將圖像數據作爲blob存儲在SQLite數據庫中並作爲字節數組進行檢索非常簡單。編碼和解碼只需要幾行代碼(對於每一行),就像一個魅力,並且效率驚人。

我會根據要求提供一個代碼示例。

祝你好運!

+0

但是,如果我想添加近5000個圖像,是否有任何問題? – user2580401

+0

我將請將可以提供一個例子 – Coderji

+0

小例子(位圖<->字節數組): 公共位圖setImageFromByteArray(字節[] byImage){ \t ByteArrayInputStream進行在新= ByteArrayInputStream的(byImage); \t return BitmapFactory.decodeStream(in); } \t 公共字節[] getByteArrayFromImage(位圖圖像​​){ \t ByteArrayOutputStream OUT =新ByteArrayOutputStream(); \t image.compress(Bitmap.CompressFormat.JPEG,80,out); \t return out.toByteArray(); } – v1k

0

我明白了!

首先確保您的應用程序啓用了存儲許可:

轉至設備設置>設備>應用程序>應用程序管理器>「你的應用」>權限>啓用存儲權限!

權限清單中:

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

所以,如果你想在你的文件存儲到創建自己的目錄,你可以使用somethibng像:

FileOutputStream outStream = null; 
File sdCard = Environment.getExternalStorageDirectory(); 
File dir = new File(sdCard.getAbsolutePath() + "/camtest"); 
dir.mkdirs(); 
String fileName = String.format("%d.jpg", System.currentTimeMillis()); 
File outFile = new File(dir, fileName); 
outStream = new FileOutputStream(outFile); 
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream); 
outStream.flush(); 
outStream.close(); 
refreshGallery(outFile); 

另外,如果你想創建一個子目錄中的默認設備DCIM文件夾,然後希望在圖庫中的單獨文件夾中查看圖像:

FileOutputStream fos= null; 
    File file = getDisc(); 
    if(!file.exists() && !file.mkdirs()) { 
     //Toast.makeText(this, "Can't create directory to store image", Toast.LENGTH_LONG).show(); 
     //return; 
     print("file not created"); 
     return; 
    } 
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmsshhmmss"); 
    String date = simpleDateFormat.format(new Date()); 
    String name = "FileName"+date+".jpg"; 
    String file_name = file.getAbsolutePath()+"/"+name; 
    File new_file = new File(file_name); 
    print("new_file created"); 
    try { 
     fos= new FileOutputStream(new_file); 
     Bitmap bitmap = viewToBitmap(iv, iv.getWidth(), iv.getHeight()); 
     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); 
     Toast.makeText(this, "Save success", Toast.LENGTH_LONG).show(); 
     fos.flush(); 
     fos.close(); 
    } catch (FileNotFoundException e) { 
     print("FNF"); 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    refreshGallery(new_file); 

幫手功能:

public void refreshGallery(File file){ 
    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); 
    intent.setData(Uri.fromFile(file)); 
    sendBroadcast(intent); 
} 

private File getDisc(){ 
    String t= getCurrentDateAndTime(); 
    File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); 
    return new File(file, "ImageDemo"); 
} 

private String getCurrentDateAndTime() { 
    Calendar c = Calendar.getInstance(); 
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); 
    String formattedDate = df.format(c.getTime()); 
    return formattedDate; 

public static Bitmap viewToBitmap(View view, int width, int height) { 
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); 
    Canvas canvas = new Canvas(bitmap); 
    view.draw(canvas); 
    return bitmap; 
} 

希望這會有所幫助!

+0

你給出正確答案了嗎? 有關內部存儲器的問題詢問 - > ** android將圖像保存到內部存儲器**有關外部存儲器的答案。 –

相關問題