Android 创建自己的Camera App
在sdk中找到/sdk/docs/guide/topics/media/camera.html#custom-camera,里面有详细的api参考
在清单文件中添加相应的权限:
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
按照官方文档,分为下面几步:
- Detect and Access Camera - Create code to check for the existence of cameras and request access.
- Create a Preview Class - Create a camera preview class that extends
SurfaceViewand implements theSurfaceHolderinterface. This class previews the live images from the camera. - Build a Preview Layout - Once you have the camera preview class, create a view layout that incorporates the preview and the user interface controls you want.
- Setup Listeners for Capture - Connect listeners for your interface controls to start image or video capture in response to user actions, such as pressing a button.
- Capture and Save Files - Setup the code for capturing pictures or videos and saving the output.
- Release the Camera - After using the camera, your application must properly release it for use by other applications.
接下来分别实现:
1、检查设备是否有照相机
/** 检查设备是否存在照相机 */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
}
2、得到一个照相机
/** 一种安全的方式获取Cameer对象的实例. */
public static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
3、新建一个名为CameraPreview的类
package com.wuyudong.mycamera; import java.io.IOException; import android.content.Context;
import android.hardware.Camera;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView; /** A basic Camera preview class */
public class CameraPreview extends SurfaceView implements
SurfaceHolder.Callback {
private static final String TAG = "CameraPreview";
private SurfaceHolder mHolder;
private Camera mCamera; public CameraPreview(Context context, Camera camera) {
super(context);
mCamera = camera; // Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed.
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
} public void surfaceCreated(SurfaceHolder holder) {
// The Surface has been created, now tell the camera where to draw the
// preview.
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d(TAG, "Error setting camera preview: " + e.getMessage());
}
} public void surfaceDestroyed(SurfaceHolder holder) {
// empty. Take care of releasing the Camera preview in your activity.
} public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it. if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
} // stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
} // set preview size and make any resize, rotate or
// reformatting changes here // start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview(); } catch (Exception e) {
Log.d(TAG, "Error starting camera preview: " + e.getMessage());
}
}
}
4、设置一个预览功能的layout,将原来布局文件中的内容替换成下面的代码
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout
android:id="@+id/camera_preview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
/> <Button
android:id="@+id/button_capture"
android:text="Capture"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</LinearLayout>
5、在清单文件中加入 android:screenOrientation="landscape" 调整相机为横向拍摄
6、在MainActivity中添加
public class MainActivity extends Activity {
private Camera mCamera;
private CameraPreview mPreview;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Create an instance of Camera
mCamera = getCameraInstance();
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
}
}
7、实现拍摄按钮的功能
(1)添加拍照回调方法
private PictureCallback mPicture = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
File pictureFile = new File("/sdcard/" + System.currentTimeMillis()+".jpg");
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (IOException e) {
Log.d("TAG", "Error accessing file: " + e.getMessage());
}
}
};
给拍照按钮添加注册事件:
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture);
}
}
);
完整的代码如下:
package com.wuyudong.mycamera; import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date; import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout; public class MainActivity extends Activity { private Camera mCamera;
private CameraPreview mPreview; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // 创建一个 Camera 的实例
mCamera = getCameraInstance(); // 创建一个预览界面
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview); // Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
mCamera.autoFocus(new AutoFocusCallback() { // 对焦 @Override
public void onAutoFocus(boolean success, Camera camera) {
// get an image from the camera
mCamera.takePicture(null, null, mPicture); }
}); }
}
);
} /** 检查设备是否存在照相机 */
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
// this device has a camera
return true;
} else {
// no camera on this device
return false;
}
} /** 一种安全的方式获取Cameer对象的实例. */
public static Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
} catch (Exception e) {
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
} private PictureCallback mPicture = new PictureCallback() { @Override
public void onPictureTaken(byte[] data, Camera camera) { File pictureFile = new File("/sdcard/" + System.currentTimeMillis()+".jpg");
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
} catch (IOException e) {
Log.d("TAG", "Error accessing file: " + e.getMessage());
}
}
}; protected void onDestory() {
if(mCamera != null) { //释放资源
mCamera.release();
mCamera = null;
}
} }
Android 创建自己的Camera App的更多相关文章
- Android Camera 使用小结。两种方法:一是调用系统camera app,二是自己写camera程序。
源文链接:http://www.cnblogs.com/franksunny/archive/2011/11/17/2252926.html Android Camera 使用小结 Android手机 ...
- android——创建camera应用(译)
只是选择相机部分来翻译.下面是主要内容 有些开发者可能需要Camera的接口,来定制自己程序的外观和特殊功能.创建自定义的Camera界面比使用using an Intent需要编写更多的代码,但是 ...
- hybird app(混合式app开发)cordova ionic 创建相应平台的app
hybird app(混合式app开发) 之ionic 框架平台 guide cordova 创建相应平台的app 1. npm install -g cordova //全局安装cordova-cl ...
- Android开发之初识Camera图像采集
/* * Android开发之初识camera图像采集 * 北京Android俱乐部群:167839253 * Created on: 2011-8-24 * Author: blueeagle * ...
- Android - 分享内容 - 接收其他APP的内容
就象程序可以发送数据给其他程序,所以也可以接收其他程序的数据.想一下用户如何和程序交互,以及想从其他程序接收什么样类型的数据.例如,一个社交程序可能对接收其他程序的文字(比如有趣的网址)感兴趣.Goo ...
- Android - 分享内容 - 给其他APP发送内容
创建一个intent时,必须要指定intent将要触发的操作.Android定义了很多操作,包括ACTION_SEND,就象可以猜到的一样,表示intent是把数据从一个activity发送给另一个, ...
- android 创建 xml文件
android创建xml文件的方法. 要操作android的外部存储,所以要在AndroidManifest.xml文件中添加权限. <uses-permission android:name= ...
- 安卓Camera APP
一.Camera package android.hardware 该类用于设定图像捕获设置,开启/关闭预览,抓拍图片以及获取帧用于编码视频.这个类是Camera服务的客户端,用 ...
- 导入android源码中的APP源码到eclipse
导入android源码中的APP源码到eclipse 一般最简单的办法就是创建新的android工程,选择create project from existing source选项,直接导入源码就OK ...
随机推荐
- php对xml文件进行CURD操作
XML是一种数据存储.交换.表达的标准: - 存储:优势在于半结构化,可以自定义schema,相比关系型二维表,不用遵循第一范式(可以有嵌套关系): - 交换:可以通过schema实现异构数据集成: ...
- 使用LinkedList模拟一个堆栈或者队列数据结构
使用LinkedList模拟一个堆栈或者队列数据结构. 堆栈:先进后出 如同一个杯子. 队列:先进先出 如同一个水管. import java.util.LinkedList; public cl ...
- ASP.NET发送电子邮件
代码: using System; using System.Collections.Generic; using System.Configuration; using System.Linq; u ...
- css3代码让页面倾斜
教大家一个方法使用CSS把整个网页倾斜,代码只有在支持CSS3.0的浏览器上有效果.目前只有IE9以上版本及firefox高版本支持,其它浏览器没有测试.代码如下 body{ -webkit-tran ...
- 快速学习JavaScript面向对象编程
到处都是属性.方法,代码极其难懂,天哪,我的程序员,你究竟在做什么?仔细看看这篇指南,让我们一起写出优雅的面向对象的JavaScript代码吧! 作为一个开发者,能否写出优雅的代码对于你的职业生涯至关 ...
- C#单纯的字母数字ASCII码转换
字母转换成数字 byte[] array = new byte[1]; //定义一组数组array array = System.Text.Encoding.ASCII.Ge ...
- .NET使用ZXing.NET生成中间带图片的二维码
很久之前就有写这样的代码了,只是一直没记录下来,偶然想写成博客. 把之前的代码封装成函数,以方便理解以及调用. 基于开源的 ZXing.NET 组件,代码如下: 先添加对ZXing.NET的引用,然后 ...
- 背水一战 Windows 10 (6) - 控件 UI: 字体的自动继承的特性, Style, ControlTemplate
[源码下载] 背水一战 Windows 10 (6) - 控件 UI: 字体的自动继承的特性, Style, ControlTemplate 作者:webabcd 介绍背水一战 Windows 10 ...
- mysql学习笔记 第五天
使用分区数据表: 分区数据表和merge数据表具有相似的作用,但是分区数据表确确实实是一个数据表 ,不像merge是列出数据表的逻辑关系,并且分区数据表可以包括像myisam以外的 的数据表.创建分区 ...
- Scalaz(24)- 泛函数据结构: Tree-数据游览及维护
上节我们讨论了Zipper-串形不可变集合(immutable sequential collection)游标,在串形集合中左右游走及元素维护操作.这篇我们谈谈Tree.在电子商务应用中对于xml, ...