我需要保护我拍摄的图像。来自android Android Training 我能够拍摄全尺寸的图像。但这不是我的需要。 我需要将完整大小的图像保存到缓存目录(/ data / data // cache),当用户离开我的应用程序时,我将删除这些缓存文件夹。
这是我的代码,该文件在缓存目录中成功创建。但文件大小为零,没有写入图像
static final int REQUEST_TAKE_PHOTO = 1;
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File file=null;
try {
String fileName = "506214";
file = File.createTempFile(fileName, null, this.getCacheDir());
} catch (IOException e) {
// Error while creating file
}
photoURI = Uri.fromFile(file);
Toast.makeText(this, photoURI.toString(), Toast.LENGTH_SHORT).show();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK){
camera_image.setImageURI(photoURI);
}
super.onActivityResult(requestCode, resultCode, data);
}
答案 0 :(得分:0)
试试这个我的朋友
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "MyImages");
imagesFolder.mkdirs(); // <----
File image = new File(imagesFolder, "image_001.jpg");
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
并且不要忘记在最明确的文件中使用dd permisoon
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
答案 1 :(得分:0)
如果您在Activity
类中,请使用this.getCacheDir()
作为File
的第一个参数,并使用第二个arg作为文件名存储在缓存目录中。
File f = new File(this.getCacheDir(), "capture_"+ imageNumber++);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
下面是我捕获并保存到缓存中直到上传到S3的方式(此代码在onActivityResult()
内部):
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
//create a file to write bitmap data
File f = new File(this.getCacheDir(), "capture_"+ imageNumber++);
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
//Convert bitmap to byte array
Bitmap bitmap = photo;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos;
try {
fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}