After taking a picture with my camera, I want to save it in that layout. I also want to save it to a File and be able to load that picture when I create the activity(so if i switch to a different activity and come back to this one). As of now, i can take the picture and display it, but if i switch activities more than once, the picture gets lost.I have the following relevant code:
I load my picture OnCreate using setImage()
:
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;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…