我有一个应用程序,允许用户通过该应用程序拍照,然后我希望将文件保存到外部存储中,然后加载该文件并将其放到imageview中。到目前为止,我拥有的代码会保存到外部存储中,但是当我尝试加载它时,它会指出该文件不存在。
public class MainActivity extends AppCompatActivity {
ImageView mImageView;
String fileName = "image.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button cameraButton = findViewById(R.id.cameraButton);
Button photoButton = findViewById(R.id.photoButton);
mImageView = findViewById(R.id.photoViewer);
if(!isExternalStorageWritable()) {
out.println("NOT WRITABLE");
}
if(!isExternalStorageReadable()) {
out.println("NOT READABLE");
}
cameraButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, 0);
}
});
photoButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
loadPhoto(fileName);
}
});
}
此方法保存拍摄的照片:
public File savePhoto() {
File filePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
//Create a new folder in the sd card / emulated external storage
File dir = new File(filePath.getAbsolutePath() + "/QuoteApp");
///storage/emulated/0/Pictures/QuoteApp/image.jpg
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile = new File(dir + "image" + ".jpg");
return mediaFile;
}
此方法将加载在上一个方法中保存的照片:
public void loadPhoto(String fileName) {
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/QuoteApp/" + fileName);
//File path is /storage/emulated/0/Pictures/QuoteApp/image.jpg
String filePath = file.getAbsolutePath();
Bitmap bitmapReturn = BitmapFactory.decodeFile(filePath);
mImageView.setImageBitmap(bitmapReturn);
}
此方法创建图像并调用savePhoto方法:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
savePhoto();
}
}
我在做什么错了?