[应用程序关闭后,我试图在imagebutton中重新加载从图库或相机中获得的图像
我已经尝试将其保存到文件并从该文件加载,但无法使其正常工作。
public class HomeFragment extends Fragment {
String photoPath = Environment.getExternalStorageDirectory() + "/myImage.jpg";
ImageButton profilePic;
Bitmap bitmap;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_home, container, false);
profilePic = (ImageButton) root.findViewById(R.id.imageButton);
bitmap = ((BitmapDrawable)profilePic.getDrawable()).getBitmap();
// set up listener on ImageButton to load method changeProfilePicture() when user clicks profilePic
profilePic.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
changeProfilePicture();
}
});
loadImageFromStorage(photoPath);
return root;
}
public void onResume() {
super.onResume();
loadImageFromStorage(photoPath);
}
public void onStart() {
super.onStart();
}
public void onPause() {
super.onPause();
}
public void onStop() {
super.onStop();
saveBitmap(bitmap);
}
public void onDestroy() {
super.onDestroy();
}
static final int REQUEST_IMAGE_CAPTURE = 1;
static final int REQUEST_GALLERY = 0;
public void changeProfilePicture() {
// dialog asks user to choose how they want to change picture
}
// override onActivityResult to allow the imageButton to be changed to picture taken from camera or gallery
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
switch (requestCode) {
case REQUEST_GALLERY:
Uri galleryImage = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), galleryImage);
bitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, false);
profilePic.setImageBitmap(bitmap);
} catch (IOException e) {
Log.i("TAG", "Exception " + e);
}
break;
case REQUEST_IMAGE_CAPTURE:
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, 200, 200, false);
profilePic.setImageBitmap(imageBitmap);
break;
}
}
}
private void saveBitmap(Bitmap bm){
File file = Environment.getExternalStorageDirectory();
File newFile = new File(file, "myImage.jpg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(newFile);
bm.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "myImage.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
profilePic.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
我正在尝试从结果中保存新的ImageButton,并在重新启动应用程序时加载它。可以使用ImageButton完成吗?可以将其保存到文件并从中加载吗?
第一步,您需要像这样从imageButton
获取位图