这篇文章给大家介绍Android 中怎么实现无预览拍照功能,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。
public void onTakePhotoClicked() {
final SurfaceView preview = new SurfaceView(this);
SurfaceHolder holder = preview.getHolder();
// deprecated setting, but required on Android versions prior to 3.0
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.addCallback(new SurfaceHolder.Callback() {
@Override
//The preview must happen at or after this point or takePicture fails
public void surfaceCreated(SurfaceHolder holder) {
Log.d(TAG, "Surface created");
camera = null;
try {
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_BACK);
Log.d(TAG, "Opened camera");
try {
camera.setPreviewDisplay(holder);
} catch (IOException e) {
throw new RuntimeException(e);
}
camera.startPreview();
Log.d(TAG, "Started preview");
//延时拍照
ThreadUtils.postOnUiThreadDelayed(new Runnable() {
@Override
public void run() {
Log.e("zgj","开始拍照");
camera.takePicture(null, null, CameraService.this);
}
},5000);
} catch (Exception e) {
if (camera != null)
camera.release();
throw new RuntimeException(e);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
});
WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
1, 1, //Must be at least 1x1
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
0,
//Don't know if this is a safe default
PixelFormat.UNKNOWN);
//Don't set the preview visibility to GONE or INVISIBLE
wm.addView(preview, params);
}
@Override
public void onPictureTaken(byte[] bytes, Camera camera) {
Log.e("zgj", "拍照结束");
File pictureDir = Environment.getExternalStorageDirectory();
if (pictureDir == null) {
Log.d("zgj",
"Error creating media file, check storage permissions!");
return;
}
try {
String pictureName = "ssss.png";
File file = new File(pictureDir + "/pic/");
if (!file.exists()) {
file.mkdir();
}
file = new File(pictureDir + "/pic/" + pictureName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes);
fos.close();
} catch (FileNotFoundException e) {
Log.d("zgj", "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d("zgj", "Error accessing file: " + e.getMessage());
}
}
关于Android 中怎么实现无预览拍照功能就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。