gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:55:05 26 4
gpt4 key购买 nike

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

我使用 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;

}

最佳答案

听起来您的代码可以正常工作,但是当 Activity 恢复时您正在丢失图像。加载您的图片 onPostResume() 而不是 onCreate() 可能是您所需要的。感觉 Activity 生命周期是您问题的关键。我有几个问题会在评论中提出。

关于java - Android:将图片保存到文件并检索它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6861820/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com