我有一个自定义相机,我想将捕获的图像保存在sd卡的文件夹中。我看过一些例子,但不知什么原因,我就是没有得到任何东西来保存(文件夹或图像)。下面是我的代码。如果有人能帮忙,那就太好了!我已经有安卓系统的许可了。WRITE_EXTERNAL_STORAGE添加到我的manifest.
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mCamera.takePicture(null, null, mPicture);
mCamera = getCameraInstance();
mPreview = new CameraPreview(CameraActivity.this, mCamera);
FrameLayout preview = (FrameLayout)findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
private Camera getCameraInstance() {
// TODO Auto-generated method stub
Camera c = null;
try {
c = Camera.open();
}
catch (Exception e) {
}
return c;
}
private PictureCallback mPicture = new PictureCallback() {
public void onPictureTaken(byte[] datas, Camera camera) {
// TODO Auto-generated method stub
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(datas);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
};
private File getOutputMediaFile() {
// TODO Auto-generated method stub
File root = Environment.getExternalStorageDirectory();
File myDir = new File(root + "/NewFolder/");
myDir.mkdirs();
if (myDir.exists()){
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image"+ n +".jpg";
File file = new File (myDir, fname);
Uri uriSavedImage = Uri.fromFile(file);
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"+ Environment.getExternalStorageDirectory())));
i.putExtra("output", uriSavedImage);
return file;
};
首先确保您已经在清单中提供了WRITE_EXTERNAL_STORAGE权限。
在某些手机上,当你从FileOutputStream写入文件时,文件不会自动创建,所以你可以试试这个:
try {
pictureFile.createNewFile();
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(datas);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
EDIT也在一个不相关的注意事项上,您正在使用的Random的实现将始终返回与种子值相同的数字。请尝试System.getCurrentMillis()为您的图像获取唯一的名称。
我有同样的问题,因为你有保存图像和我们的代码是相似的。我不知道这是否重要,但我正在使用一个实际的设备。对我来说有效的方法是在手机上运行这个项目,断开手机与电脑的连接,然后进行测试。经过测试,我可以将手机重新连接到电脑上,看看图片和文件夹是否还在。