我正在构建一个 Android 应用程序,它会拍照然后立即进入裁剪屏幕。我不知道如何在不降级的情况下传递图像(即,如果我要将其放入捆绑包中),所以我决定保存图像并将其从卡中拉回。
现在,当我试图在新的crop_view 中取回图像时,它紧跟在camera_view 之后,应用程序在下面代码中指示的行上抛出了一个空指针异常。图片实际上是在 Pictures/MyApp/IMG_APP.jpg 设置的,其中“图片”是我的默认图片目录。
public Bitmap getImage() {
Bitmap toReturn = null;
File root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
ImageView IV = (ImageView) findViewById(R.id.crop_view);
toReturn = BitmapFactory.decodeFile(root+"/MyApp/IMG_APP.jpg");
IV.setImageBitmap(toReturn);
return toReturn;// TODO Fix this line. It is breaking here with a null pointer exception.
}
下面是保存图片的代码。我已经通过在另一个应用程序中检查实际的 sd 卡来确认它正在保存。
void onPictureJpeg(byte[] bitmapdata, Camera camera) {
int i = bitmapdata.length;
Log.d(TAG, String.format("bytes = %d", i));
File f = IMGP_Photo_Handler.generateTimeStampPhotoFile();
try {
OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(f));
outputStream.write(bitmapdata);
outputStream.flush();
outputStream.close();
exceptionCaught = false;
} catch (Exception e) {
Log.e(TAG, "Error accessing photo output file:" + e.getMessage());
Toast
.makeText(IMGP_Camera.this, "Cannot save file. \nPlease mount an external SD Card", Toast.LENGTH_LONG)
.show();
exceptionCaught = true;// To get this to not start the next intent if the file save doesn't work.
}
if(!exceptionCaught){
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
Intent intent = new Intent();
intent.setClass(IMGP_Camera.this, IMGP_Crop.class);
intent.putExtra("po","3265695");
startActivity(intent);
}
finish();
}
最后是我的 photo_handler:
public static Uri photoFileUri = null;
public static File getPhotoDirectory() {
File outputDir = null;
String externalStorageState = Environment.getExternalStorageState();
if (externalStorageState.equals(Environment.MEDIA_MOUNTED)) {
File pictureDir =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
outputDir = new File(pictureDir, "MyApp");
if(!outputDir.exists()) {
if(!outputDir.mkdirs()) {
String message = "Failed to create directory:" + outputDir.getAbsolutePath();
Log.e(TAG, message);
outputDir = null;
}
}
}
return outputDir;
}
public static File generateTimeStampPhotoFile() {
File photoFile = null;
File outputDir = getPhotoDirectory();
if (outputDir != null) {
String photoFileName = "IMG_APP.jpg";
photoFile = new File(outputDir, photoFileName);
}
return photoFile;
}
public static Uri generateTimeStampPhotoFileUri() {
photoFileUri = null;
File photoFile = generateTimeStampPhotoFile() ;
if (photoFile != null) {
photoFileUri = Uri.fromFile(photoFile);
}
return photoFileUri;
}
public static Uri getFile(){
return photoFileUri;
}