Android:将图片保存到文件并检索它

用我的相机拍照后,我想将它保存在那个布局中。 我还想将它保存到文件中,并且能够在创建活动时加载该图片(因此,如果我切换到不同的活动并返回到此活动)。 截至目前,我可以拍摄并显示它,但如果我不止一次切换活动,图片就会丢失。我有以下相关代码:

我使用setImage()加载我的图片OnCreate:

 private void setImage(){ if (loadPicture("hello", bitmap) != null) { Toast.makeText(this, "not null", Toast.LENGTH_SHORT).show(); imageView.setImageBitmap(loadPicture("hello", bitmap)); } } private void takePicture(){ Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); File photo = new File(Environment.getExternalStorageDirectory(), "Pic.jpg"); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo)); imageUri = Uri.fromFile(photo); startActivityForResult(intent, 0); } public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Uri selectedImage = imageUri; getContentResolver().notifyChange(selectedImage, null); ContentResolver cr = getContentResolver(); try { bitmap = android.provider.MediaStore.Images.Media .getBitmap(cr, selectedImage); imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, bitmap.getHeight()/2, bitmap.getWidth()/2, false)); //**Where I save the picture** savePicture("hello", bitmap, getApplicationContext()); } private void savePicture(String filename, Bitmap b, Context ctx){ try { ObjectOutputStream oos; FileOutputStream out;// = new FileOutputStream(filename); out = ctx.openFileOutput(filename, Context.MODE_PRIVATE); oos = new ObjectOutputStream(out); b.compress(Bitmap.CompressFormat.PNG, 100, oos); oos.close(); oos.notifyAll(); out.notifyAll(); out.close(); } catch (Exception e) { e.printStackTrace(); } } private Bitmap loadPicture(String filename, Bitmap b){ // Drawable myImage = null; try { FileInputStream fis = openFileInput(filename); ObjectInputStream ois = null; try { ois = new ObjectInputStream(fis); } catch (StreamCorruptedException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } // myImage = Drawable.createFromStream(ois, filename); b = BitmapFactory.decodeStream(ois); try { ois.close(); fis.close(); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } // return myImage; return b; } 

这听起来像你的代码有效,但是当活动回来时你正在失去你的形象。 加载你的图片onPostResume()而不是onCreate()可能是你需要的。 感觉活动生命周期是您问题的关键。 我有几个问题需要注意。

 out = ctx.openFileOutput(filename, Context.MODE_PRIVATE); 

尝试切换到:

 out = ctx.openFileOutput(filename, Context.MODE_WORLD_READABLE);