Android实现简单拍照(使用摄像头)

Android实现简单拍照(使用摄像头)_第1张图片

由于左边的部分是摄像头拍摄的内容,所以截图软件获取不到内容,测试手机小米(Mi One Plus)

截图缩小:

Android实现简单拍照(使用摄像头)_第2张图片

补充一点:拍照得到的图像的大小(Size)是可以设置的,只不过在我这个程序里面使用是默认的大小。

设置方法是:

获得摄像头支持的大小List

List<Camera.Size> sizes = myCamera.getPArameters().getSupportedPictureSizes();

在Camera.Parameters中使用下面这个函数即可

setPictureSize(int width, int height)

修改:

拍照的代码修改为:

captureButton.setOnClickListener(new OnClickListener() {// 拍照按钮事件
	@Override
	public void onClick(View v) {
		// 先启动自动对焦
		mCamera.autoFocus(new AutoFocusCallback() {
			@Override
			public void onAutoFocus(boolean success,
					Camera camera) {
				if(success){
					mCamera.takePicture(mShutter, null, mPicture);
				}
			}
		});
	}
});


要控制摄像头和拍照首先需要在Manifest中添加权限如下:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />

然后需要实现两个类,一个是Activity类,一个SurfaceView类:

SurfaceView类是用来获取摄像头的实景内容。

CameraUseActivity.java

package com.zeph.android.camera;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;

public class CameraUseActivity extends Activity {
	/** 图片媒体类型 **/
	public static final int MEDIA_TYPE_IMAGE = 1;
	/** 摄像头类的对象 **/
	private Camera mCamera;
	/** SurfaceView对象 **/
	private CameraPreview mPreview;
	/** 拍照按钮 **/
	private Button captureButton;
	/** 返回摄像头 **/
	private Button cameraButton;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Window window = getWindow();// 得到窗口
		requestWindowFeature(Window.FEATURE_NO_TITLE);// 没有标题
		window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);// 设置全屏
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// 保持屏幕亮

		setContentView(R.layout.main);

		captureButton = (Button) findViewById(R.id.button_capture);
		captureButton.setOnClickListener(new OnClickListener() {// 拍照按钮事件
					@Override
					public void onClick(View v) {
						// 先启动自动对焦
						mCamera.autoFocus(new AutoFocusCallback() {
							@Override
							public void onAutoFocus(boolean success,
									Camera camera) {

							}
						});
						// 1.75秒后启动拍照
						Timer timer = new Timer();
						timer.schedule(new TimerTask() {
							@Override
							public void run() {
								// 拍照函数
								mCamera.takePicture(mShutter, null, mPicture);
							}
						}, 1750);
					}
				});
		cameraButton = (Button) findViewById(R.id.button_camera);
		cameraButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// 返回按钮(拍完照片之后需要重新启动Camera的Preview)
				mCamera.startPreview();
			}
		});
		// 获取Camera对象的实例
		mCamera = getCameraInstance();
		// 初始化SurfaceView
		mPreview = new CameraPreview(this, mCamera);
		FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
		// 将SurfaceView添加到FrameLayout中
		preview.addView(mPreview);
		// 设置相机的属性
		Camera.Parameters params = mCamera.getParameters();
		// JPEG质量设置到最好
		params.setJpegQuality(100);
		// 散光灯模式设置为自动调节
		params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
		mCamera.setParameters(params);
	}

	// PictureCallback回调函数实现
	private PictureCallback mPicture = new PictureCallback() {
		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
			if (pictureFile == null) {
				return;
			}
			// 将照片数据data写入指定的文件
			try {
				FileOutputStream fos = new FileOutputStream(pictureFile);
				fos.write(data);
				fos.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	};
	// 快门的回调函数实现
	private ShutterCallback mShutter = new ShutterCallback() {
		@Override
		public void onShutter() {

		}
	};

	// 释放Camera对象(务必实现)
	private void releaseCamera() {
		if (mCamera != null) {
			mCamera.release();
			mCamera = null;
		}
	}

	public static Camera getCameraInstance() {
		Camera c = null;
		try {
			c = Camera.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return c;
	}

	/**
	 * 在指定路径创建照片文件
	 * 
	 * @param type
	 * @return
	 */
	public static File getOutputMediaFile(int type) {
		// 指定照片存放的目录,在SD根目录下的一个文件夹中
		File mediaStorageDir = new File(
				Environment
						.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
				"CameraUseApp");
		// 文件夹不存在,则创建该文件夹
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("CameraUse", "failed to create directory");
				return null;
			}
		}
		String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
				.format(new Date());
		// 创建照片文件
		File mediaFile;
		if (type == MEDIA_TYPE_IMAGE) {
			mediaFile = new File(mediaStorageDir.getPath() + File.separator
					+ "IMG_" + timeStamp + ".jpg");
		} else {
			return null;
		}
		return mediaFile;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// 触摸屏幕自动对焦
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			mCamera.autoFocus(new AutoFocusCallback() {
				@Override
				public void onAutoFocus(boolean success, Camera camera) {

				}
			});
		}
		return super.onTouchEvent(event);
	}

	@Override
	protected void onPause() {
		super.onPause();
		releaseCamera();
	}
}

CameraPreview.java

package com.zeph.android.camera;

import java.io.IOException;

import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class CameraPreview extends SurfaceView implements
		SurfaceHolder.Callback {
	private SurfaceHolder mHolder;
	private Camera mCamera;

	public CameraPreview(Context context, Camera camera) {
		super(context);
		mCamera = camera;
		mHolder = getHolder();
		mHolder.addCallback(this);
		mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (holder.getSurface() == null)
			return;
		try {
			mCamera.setPreviewDisplay(holder);
		} catch (IOException e) {
			e.printStackTrace();
		}
		mCamera.startPreview();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
		if (mHolder.getSurface() == null)
			return;
		mCamera.stopPreview();
		try {
			mCamera.setPreviewDisplay(mHolder);
		} catch (IOException e) {
			e.printStackTrace();
		}
		mCamera.startPreview();
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {

	}

}

main.xml,main.xml中的FrameLayout是摄像头拍摄内容的预览位置

<?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:baselineAligned="false"
    android:orientation="horizontal" >

    <FrameLayout
        android:id="@+id/camera_preview"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="1" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:orientation="vertical" >

        <Button
            android:id="@+id/button_capture"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginBottom="5dip"
            android:text="@string/Capture" />

        <Button
            android:id="@+id/button_camera"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="@string/Camera" />
    </LinearLayout>

</LinearLayout>

由于新版的ADT和SDK都推荐android:text里的值使用strings.xml,所以所有的文字内容都放在了strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, CameraUseActivity!</string>
    <string name="app_name">摄像头</string>
    <string name="Capture">拍照</string>
    <string name="Camera">返回</string>

</resources>

由于拍摄的时候,要求画面横向,所以要记得在Manifest中添加:

android:screenOrientation="landscape"

完整的Manifest.xml如下:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.zeph.android.camera"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="9" />

    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".CameraUseActivity"
            android:label="@string/app_name"
            android:screenOrientation="landscape" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

代码参考:http://developer.android.com/guide/topics/media/camera.html

拍照的效果图,效果真一般~~~

Android实现简单拍照(使用摄像头)_第3张图片



你可能感兴趣的:(android,String,layout,null,button,encoding)