我想在Android中使用下面的代碼拍照。當前的代碼不起作用,即我無法在手機存儲器中找到圖片。不能在Android中拍照
public class CameraShooting implements SurfaceHolder.Callback {
Context context;
Camera camera;
CameraInfo camerainfo;
Camera.Parameters paras;
SurfaceView surfaceview;
SurfaceHolder surfaceholder;
PictureCallback picturecallback;
SurfaceHolder.Callback callback = (SurfaceHolder.Callback) this;
public CameraShooting(Context context) {
this.context = context;
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
surfaceview = new SurfaceView(context);
surfaceholder = surfaceview.getHolder();
surfaceholder.addCallback(callback);
}
};
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
int numbersofCamera = camera.getNumberOfCameras();
camerainfo = new CameraInfo();
/*
* for(int i =0; i < numbersofCamera; i++){ Camera.getCameraInfo(i,
* camerainfo); if (camerainfo.facing ==
* CameraInfo.CAMERA_FACING_FRONT){ camera.open(i); }}
*/
camera.open(0);
try {
camera.setPreviewDisplay(surfaceholder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
camera.startPreview();
camera.takePicture(null, null, mPicture);
Toast.makeText(context, "Picture taken", Toast.LENGTH_SHORT).show();
};
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
private PictureCallback mPicture = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS
), "picture taken");
try {
OutputStream fos = new BufferedOutputStream(new FileOutputStream(pictureFile));
fos.write(data);
fos.close();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
};
};
}
注意,我已經包含
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
只需在'pictureFile'後面加一個調試斷點,並查看新文件的保存位置。 – ChuongPham
您是否嘗試過,看看是否有任何錯誤?你能看到數據的內容是正確的嗎? – YKa
您的回撥中的「catch」塊沒有任何功能。始終確保至少在'catch'塊中使用'e.printStackTrace()'。我的猜測是該目錄不存在,並且正在拋出一個'FileNotFoundException'。我最近創建了一個相機應用程序並在手機上使用了'Environment.DIRECTORY_DOWNLOADS' - 該目錄不存在,但是當我手動創建它時,一切正常。 – Squonk