Android Camera——拍照
Camera定义在package android.hardware内,具体用法SDK里叙述的可清楚了。架构解析什么的网上也有很多,没什么必要讲了(你认为我不知道我会说吗)。
这篇呢,就整理了下Camera的拍照,其他还木有==
一、系统相机
1)调用方式
系统相机的入口Action:MediaStore.ACTION_IMAGE_CAPTURE。只需以startActivityForResult(…)启动该Activity即可。
- // 调用系统相机
- Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
- startActivityForResult(intent, 1);
2)处理方式
在onActivityResult(…)中,处理返回信息。
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (1 == requestCode) { // 系统相机返回处理
- if (resultCode == Activity.RESULT_OK) {
- Bitmap cameraBitmap = (Bitmap) data.getExtras().get("data");
- …… // 处理图像
- }
- takeBtn1.setClickable(true);
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
二、自定义相机
1)照相预览
继承SufaceView写自己的预览界面,继而放到你的照相Activity的布局里。这里面有个相机拍照监听接口,用于在Activity里再处理这些操作。
- public class CameraPreview extends SurfaceView implements
- SurfaceHolder.Callback {
- /** LOG标识 */
- // private static final String TAG = "CameraPreview";
- /** 分辨率 */
- public static final int WIDTH = 1024;
- public static final int HEIGHT = 768;
- /** 监听接口 */
- private OnCameraStatusListener listener;
- private SurfaceHolder holder;
- private Camera camera;
- // 创建一个PictureCallback对象,并实现其中的onPictureTaken方法
- private PictureCallback pictureCallback = new PictureCallback() {
- // 该方法用于处理拍摄后的照片数据
- @Override
- public void onPictureTaken(byte[] data, Camera camera) {
- // 停止照片拍摄
- camera.stopPreview();
- camera = null;
- // 调用结束事件
- if (null != listener) {
- listener.onCameraStopped(data);
- }
- }
- };
- // Preview类的构造方法
- public CameraPreview(Context context, AttributeSet attrs) {
- super(context, attrs);
- // 获得SurfaceHolder对象
- holder = getHolder();
- // 指定用于捕捉拍照事件的SurfaceHolder.Callback对象
- holder.addCallback(this);
- // 设置SurfaceHolder对象的类型
- holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
- }
- // 在surface创建时激发
- public void surfaceCreated(SurfaceHolder holder) {
- // Log.e(TAG, "==surfaceCreated==");
- // 获得Camera对象
- camera = Camera.open();
- try {
- // 设置用于显示拍照摄像的SurfaceHolder对象
- camera.setPreviewDisplay(holder);
- } catch (IOException e) {
- e.printStackTrace();
- // 释放手机摄像头
- camera.release();
- camera = null;
- }
- }
- // 在surface销毁时激发
- public void surfaceDestroyed(SurfaceHolder holder) {
- // Log.e(TAG, "==surfaceDestroyed==");
- // 释放手机摄像头
- camera.release();
- }
- // 在surface的大小发生改变时激发
- public void surfaceChanged(final SurfaceHolder holder, int format, int w,
- int h) {
- // Log.e(TAG, "==surfaceChanged==");
- try {
- // 获取照相机参数
- Camera.Parameters parameters = camera.getParameters();
- // 设置照片格式
- parameters.setPictureFormat(PixelFormat.JPEG);
- // 设置预浏尺寸
- parameters.setPreviewSize(WIDTH, HEIGHT);
- // 设置照片分辨率
- parameters.setPictureSize(WIDTH, HEIGHT);
- // 设置照相机参数
- camera.setParameters(parameters);
- // 开始拍照
- camera.startPreview();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- // 停止拍照,并将拍摄的照片传入PictureCallback接口的onPictureTaken方法
- public void takePicture() {
- // Log.e(TAG, "==takePicture==");
- if (camera != null) {
- // 自动对焦
- camera.autoFocus(new AutoFocusCallback() {
- @Override
- public void onAutoFocus(boolean success, Camera camera) {
- if (null != listener) {
- listener.onAutoFocus(success);
- }
- // 自动对焦成功后才拍摄
- if (success) {
- camera.takePicture(null, null, pictureCallback);
- }
- }
- });
- }
- }
- // 设置监听事件
- public void setOnCameraStatusListener(OnCameraStatusListener listener) {
- this.listener = listener;
- }
- /**
- * 相机拍照监听接口
- */
- public interface OnCameraStatusListener {
- // 相机拍照结束事件
- void onCameraStopped(byte[] data);
- // 拍摄时自动对焦事件
- void onAutoFocus(boolean success);
- }
- }
2)照相活动
就是我们自己做的照相Activity了。完成后调用自己的相机,也就是跳转入这个Activity。这里面,照片以自定义路径的形式存入的媒体库。
- public class CameraActivity extends Activity implements
- CameraPreview.OnCameraStatusListener {
- public static final Uri IMAGE_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
- public static final String PATH = Environment.getExternalStorageDirectory()
- .toString() + "/AndroidMedia/";
- private CameraPreview mCameraPreview;
- private ImageView focusView;
- private boolean isTaking = false; // 拍照中
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- // 设置横屏
- setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
- // 设置全屏
- requestWindowFeature(Window.FEATURE_NO_TITLE);
- getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
- WindowManager.LayoutParams.FLAG_FULLSCREEN);
- // 设置布局视图
- setContentView(R.layout.camera);
- // 照相预览界面
- mCameraPreview = (CameraPreview) findViewById(R.id.preview);
- mCameraPreview.setOnCameraStatusListener(this);
- // 焦点图片
- focusView = (ImageView) findViewById(R.id.focusView);
- }
- /**
- * 触屏事件
- */
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- if (event.getAction() == MotionEvent.ACTION_DOWN && !isTaking) {
- isTaking = true;
- mCameraPreview.takePicture();
- }
- return super.onTouchEvent(event);
- }
- /**
- * 存储图像并将信息添加入媒体数据库
- */
- private Uri insertImage(ContentResolver cr, String name, long dateTaken,
- String directory, String filename, Bitmap source, byte[] jpegData) {
- OutputStream outputStream = null;
- String filePath = directory + filename;
- try {
- File dir = new File(directory);
- if (!dir.exists()) {
- dir.mkdirs();
- }
- File file = new File(directory, filename);
- if (file.createNewFile()) {
- outputStream = new FileOutputStream(file);
- if (source != null) {
- source.compress(CompressFormat.JPEG, 75, outputStream);
- } else {
- outputStream.write(jpegData);
- }
- }
- } catch (FileNotFoundException e) {
- e.printStackTrace();
- return null;
- } catch (IOException e) {
- e.printStackTrace();
- return null;
- } finally {
- if (outputStream != null) {
- try {
- outputStream.close();
- } catch (Throwable t) {
- }
- }
- }
- ContentValues values = new ContentValues(7);
- values.put(MediaStore.Images.Media.TITLE, name);
- values.put(MediaStore.Images.Media.DISPLAY_NAME, filename);
- values.put(MediaStore.Images.Media.DATE_TAKEN, dateTaken);
- values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
- values.put(MediaStore.Images.Media.DATA, filePath);
- return cr.insert(IMAGE_URI, values);
- }
- /**
- * 相机拍照结束事件
- */
- @Override
- public void onCameraStopped(byte[] data) {
- Log.e("onCameraStopped", "==onCameraStopped==");
- // 创建图像
- Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
- // 系统时间
- long dateTaken = System.currentTimeMillis();
- // 图像名称
- String filename = DateFormat.format("yyyy-MM-dd kk.mm.ss", dateTaken)
- .toString() + ".jpg";
- // 存储图像(PATH目录)
- Uri uri = insertImage(getContentResolver(), filename, dateTaken, PATH,
- filename, bitmap, data);
- // 返回结果
- Intent intent = getIntent();
- intent.putExtra("uriStr", uri.toString());
- intent.putExtra("dateTaken", dateTaken);
- // intent.putExtra("filePath", PATH + filename);
- // intent.putExtra("orientation", orientation); // 拍摄方向
- setResult(20, intent);
- // 关闭当前Activity
- finish();
- }
- /**
- * 拍摄时自动对焦事件
- */
- @Override
- public void onAutoFocus(boolean success) {
- // 改变对焦状态图像
- if (success) {
- focusView.setImageResource(R.drawable.focus2);
- } else {
- focusView.setImageResource(R.drawable.focus1);
- Toast.makeText(this, "焦距不准,请重拍!", Toast.LENGTH_SHORT).show();
- isTaking = false;
- }
- }
- }
3)相机调用&处理
- // 调用自定义相机
- Intent intent = new Intent(this, CameraActivity.class);
- startActivityForResult(intent, 2);
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- if (2 == requestCode) { // 自定义相机返回处理
- // 拍照成功后,响应码是20
- if (resultCode == 20) {
- Bundle bundle = data.getExtras();
- // 获得照片uri
- Uri uri = Uri.parse(bundle.getString("uriStr"));
- // 获得拍照时间
- long dateTaken = bundle.getLong("dateTaken");
- try {
- // 从媒体数据库获取该照片
- Bitmap cameraBitmap = MediaStore.Images.Media.getBitmap(
- getContentResolver(), uri);
- previewBitmap(cameraBitmap); // 预览图像
- // 从媒体数据库删除该照片(按拍照时间)
- getContentResolver().delete(
- CameraActivity.IMAGE_URI,
- MediaStore.Images.Media.DATE_TAKEN + "="
- + String.valueOf(dateTaken), null);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- takeBtn2.setClickable(true);
- }
- super.onActivityResult(requestCode, resultCode, data);
- }
三、我加的相机蒙版^^
这个最重要了,就是为了这个才把这还未完工的工程放上来的。
布局文件里面我们在加一个自定义的MaskSurfaceView,注意放在相机预览的前面,并要设置成透明(包括重刷图层的时候也要注意透明度)。
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:gravity="center"
- android:orientation="horizontal" >
- <RelativeLayout
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:layout_weight="1" >
- <org.join.meida.camera.takephoto.MaskSurfaceView
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" />
- <org.join.meida.camera.takephoto.CameraPreview
- android:id="@+id/preview"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent" />
- <ImageView
- android:id="@+id/focusView"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_centerInParent="true"
- android:src="@drawable/focus1" />
- </RelativeLayout>
- </LinearLayout>
蒙版来啦,注意到心了没有?(3d爱心是网上别人实现的)
- public class MaskSurfaceView extends SurfaceView implements
- SurfaceHolder.Callback, Runnable {
- // 定义SurfaceHolder对象
- private SurfaceHolder mSurfaceHolder;
- // 循环标记
- private boolean loop = true;
- // 循环间隔
- private static final long TIME = 300;
- // 计数器
- private int mCount;
- // 绘制方式
- private int mode;
- public MaskSurfaceView(Context context, AttributeSet attrs) {
- super(context, attrs);
- mSurfaceHolder = getHolder(); // 获取SurfaceHolder
- mSurfaceHolder.addCallback(this); // 添加回调
- mSurfaceHolder.setFormat(PixelFormat.TRANSLUCENT); // 设置透明
- }
- // 在surface创建时激发
- @Override
- public void surfaceCreated(SurfaceHolder holder) {
- mode = new Random().nextInt(2); // 随机一个[0-2)数
- new Thread(this).start(); // 开始绘制
- }
- // 在surface的大小发生改变时激发
- @Override
- public void surfaceChanged(SurfaceHolder holder, int format, int width,
- int height) {
- }
- // 在surface销毁时激发
- @Override
- public void surfaceDestroyed(SurfaceHolder holder) {
- loop = false;
- }
- @Override
- public void run() {
- while (loop) {
- try {
- Thread.sleep(TIME);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- synchronized (mSurfaceHolder) {
- drawMask();
- }
- }
- }
- /**
- * 绘制蒙版
- */
- private void drawMask() {
- // 锁定画布,得到canvas
- Canvas mCanvas = mSurfaceHolder.lockCanvas();
- // 避免surface销毁后,线程唤醒仍进入绘制
- if (mSurfaceHolder == null || mCanvas == null)
- return;
- int w = mCanvas.getWidth();
- int h = mCanvas.getHeight();
- /* 创建一个画笔 */
- Paint mPaint = new Paint();
- mPaint.setAntiAlias(true); // 设置抗锯齿
- mPaint.setColor(0x00000000); // 设置透明黑色
- mCanvas.drawRect(0, 0, w, h, mPaint); // 重绘背景
- setPaintColor(mPaint); // 循环设置画笔颜色
- mPaint.setStyle(Paint.Style.STROKE); // 描边
- if (0 == mode) {
- drawHeart2D(mCanvas, mPaint, w / 2, h / 2, h / 2); // 画一个2d爱心
- } else {
- drawHeart3D(mCanvas, mPaint); // 画一个3d爱心
- }
- // 绘制后解锁,绘制后必须解锁才能显示
- mSurfaceHolder.unlockCanvasAndPost(mCanvas);
- }
- /** 画一个2d爱心(半圆+sin曲线) */
- private void drawHeart2D(Canvas mCanvas, Paint mPaint, int centerX,
- int centerY, float height) {
- float r = height / 4;
- /* 心两半圆结点处 */
- float topX = centerX;
- float topY = centerY - r;
- /* 左上半圆 */
- RectF leftOval = new RectF(topX - 2 * r, topY - r, topX, topY + r);
- mCanvas.drawArc(leftOval, 180f, 180f, false, mPaint);
- /* 右上半圆 */
- RectF rightOval = new RectF(topX, topY - r, topX + 2 * r, topY + r);
- mCanvas.drawArc(rightOval, 180f, 180f, false, mPaint);
- /* 下半两sin曲线 */
- float base = 3 * r;
- double argu = Math.PI / 2 / base;
- float y = base, value;
- while (y >= 0) {
- value = (float) (2 * r * Math.sin(argu * (base - y)));
- mCanvas.drawPoint(topX - value, topY + y, mPaint);
- mCanvas.drawPoint(topX + value, topY + y, mPaint);
- y -= 1;
- }
- // 1)心形函数:x²+(y-³√x²)²=1
- // >> x^2+(y-(x^2)^(1/3))^2=1
- //
- // 2)心形的各种画法:
- // >> http://woshao.com/article/1a855728bda511e0b40e000c29fa3b3a/
- //
- // 3)笛卡尔情书的秘密——心形函数的绘制
- // >> http://www.cssass.com/blog/index.php/2010/808.html
- }
- /** 画一个3d爱心 */
- private void drawHeart3D(Canvas mCanvas, Paint mPaint) {
- int w = mCanvas.getWidth();
- int h = mCanvas.getHeight();
- /* 画一个3d爱心 */
- int i, j;
- double x, y, r;
- for (i = 0; i <= 90; i++) {
- for (j = 0; j <= 90; j++) {
- r = Math.PI / 45 * i * (1 - Math.sin(Math.PI / 45 * j)) * 20;
- x = r * Math.cos(Math.PI / 45 * j) * Math.sin(Math.PI / 45 * i)
- + w / 2;
- y = -r * Math.sin(Math.PI / 45 * j) + h / 4;
- mCanvas.drawPoint((float) x, (float) y, mPaint);
- }
- }
- }
- /** 循环设置画笔颜色 */
- private void setPaintColor(Paint mPaint) {
- mCount = mCount < 100 ? mCount + 1 : 0;
- switch (mCount % 6) {
- case 0:
- mPaint.setColor(Color.BLUE);
- break;
- case 1:
- mPaint.setColor(Color.GREEN);
- break;
- case 2:
- mPaint.setColor(Color.RED);
- break;
- case 3:
- mPaint.setColor(Color.YELLOW);
- break;
- case 4:
- mPaint.setColor(Color.argb(255, 255, 181, 216));
- break;
- case 5:
- mPaint.setColor(Color.argb(255, 0, 255, 255));
- break;
- default:
- mPaint.setColor(Color.WHITE);
- break;
- }
- }
- }
四、后记
今天是几号来着?T^T。
附件:http://down.51cto.com/data/2359820
本文转自winorlose2000 51CTO博客,原文链接:http://blog.51cto.com/vaero/779942,如需转载请自行联系原作者