本例在调用摄像头实现拍照中,可以调整拍照以及保存的照片的方向,调节焦距,并实现自动对焦
package com.example.camera1;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.xmlpull.v1.XmlPullParser;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.text.format.DateFormat;
import android.util.Log;
import android.util.Xml;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;
public class CameraActivity extends Activity {
private SurfaceView surfaceView;
private Button saveButton;
private Button cancelButton;
private Camera camera;
private SeekBar seekBar;
private int setFixPictureWidth = 0;//设置最适合当前手机的图片宽度
private int setFixPictureHeight = 0;//设置最适合当前手机的图片高度
private int maxPictureSize = 5000000;//设置一个固定的最大尺寸
private SurfaceHolder surfaceHolder;
private String photoPath = "/sdcard/";// 照片保存路径
private Boolean isSupportAutoFous = false;// 是否支持自动聚焦,默认不支持
private String photoName;
private Camera.PictureCallback pictureCallback = new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
try {// 获得图片
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
String photoName = new DateFormat().format("yyyyMMdd_hhmmss",
Calendar.getInstance(Locale.CHINA)) + ".jpg";
File file = new File(photoPath + photoName1);
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);// 将图片压缩到流中
bos.flush();// 输出
bos.close();// 关闭
} catch (Exception e) {
e.printStackTrace();
}
// camera.startPreview();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
// 设置拍摄方向
// this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
surfaceView = (SurfaceView) findViewById(R.id.camera_priview);
saveButton = (Button) findViewById(R.id.camera_save);
cancelButton = (Button) findViewById(R.id.camera_cancel);
seekBar = (SeekBar) findViewById(R.id.seekbar_zoom);
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
setZoom(seekBar.getProgress());
}
});
isSupportAutoFous = this.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_AUTOFOCUS);
surfaceHolder = surfaceView.getHolder();
// 设置surface不需要自己的维护缓存区
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceHolder.addCallback(surfaceCallback);
saveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Camera.Parameters parameters = setCameraParms();
camera.setParameters(parameters);
camera.takePicture(null, null, pictureCallback);
}
});
cancelButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
camera.startPreview();
}
});
SurfaceHolder.Callback surfaceCallback = new SurfaceHolder.Callback() {
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
// 关闭预览并释放资源
camera.stopPreview();
camera.release();
camera = null;
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
camera = Camera.open();
Log.e("CameraActivity", "摄像头Open完成");
try {
camera.setPreviewDisplay(holder);
} catch (IOException e) {
camera.release();
camera = null;
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
Camera.Parameters parameters = setCameraParms();
List<Camera.Size> mSupportedsizeList = parameters.getSupportedPictureSizes();
if (mSupportedsizeList.size() > 1) {
Iterator<Camera.Size> itos = mSupportedsizeList.iterator();
while (itos.hasNext()) {
Camera.Size curSize = itos.next();
int carSupportSize = curSize.width * curSize.height;
int fixPictureSize = setFixPictureWidth * setFixPictureHeight;
if (carSupportSize > fixPictureSize
&& fixPictureSize < maxPictureSize) {
setFixPictureWidth = curSize.width;
setFixPictureHeight = curSize.height;
}
}
}
if (setFixPictureWidth != 0 && setFixPictureHeight != 0){
parameters.setPictureSize(setFixPictureWidth, setFixPictureHeight);
parameters.setJpegQuality(100);
camera.setDisplayOrientation(90);
camera.setParameters(parameters);
}
camera.startPreview();
if (isSupportAutoFous) {
camera.autoFocus(new AutoFocusCallback() {
@Override
public void onAutoFocus(boolean focused, Camera camera) {
// TODO Auto-generated method stub
/*实现自动对焦拍照
if(focused){
Camera.Parameters parameters = setCameraParms();
camera.setParameters(parameters);
camera.takePicture(null, null, pictureCallback);
}*/
}
});
}
}
};
/**
* 方向变化监听器,监听传感器方向的改变
*/
public class MyOrientationDetector extends OrientationEventListener {
int Orientation;
public MyOrientationDetector(Context context) {
super(context);
}
@Override
public void onOrientationChanged(int orientation) {
Log.i("MyOrientationDetector ", "onOrientationChanged:"
+ orientation);
this.Orientation = orientation;
Log.d("MyOrientationDetector", "当前的传感器方向为" + orientation);
}
public int getOrientation() {
return Orientation;
}
}
/** 设置相机焦距 **/
private void setZoom(int mValue) {
seekBar.setMax(camera.getParameters().getMaxZoom());
Camera.Parameters parameters = camera.getParameters();
parameters.setZoom(mValue);
camera.setParameters(parameters);
}
private Camera.Parameters setCameraParms(){
MyOrientationDetector cameraOrientation = new MyOrientationDetector(
CameraActivity.this);
int orientation = cameraOrientation.getOrientation();
Camera.Parameters parameters = camera.getParameters();
parameters.setPictureFormat(ImageFormat.JPEG);
parameters.setPreviewSize(800, 480);
parameters.setRotation(90);
parameters.set("rotation", 90);
if ((orientation >= 45) && (orientation < 135)) {
parameters.setRotation(180);
parameters.set("rotation", 180);
}
if ((orientation >= 135) && (orientation < 225)) {
parameters.setRotation(270);
parameters.set("rotation", 270);
}
if ((orientation >= 225) && (orientation < 315)) {
parameters.setRotation(0);
parameters.set("rotation", 0);
}
return parameters;
}
@Override
protected void onDestroy() {
super.onDestroy();
// File file = new File(photoPath + photoName);
// if (file.exists()) {
// file.delete();
}
}
}
布局文件activity_camera.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CameraActivity" >
<RelativeLayout
android:id="@+id/a"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<SurfaceView
android:id="@+id/camera_priview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_vertical|center_horizontal"
android:layout_marginBottom="55dp" />
<SeekBar
android:id="@+id/seekbar_zoom"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="center_vertical"
android:layout_marginBottom="55dp"
android:progressDrawable="@drawable/seekbar_style"
android:thumb="@drawable/ic_launcher"
android:thumbOffset="0dp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/a"
android:background="#000">
<Button
android:id="@+id/camera_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="#000"
android:textColor="#fff"
android:text="拍照" />
<Button
android:id="@+id/camera_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#000"
android:textColor="#fff"
android:text="取消" />
</RelativeLayout>
</RelativeLayout>
添加权限
<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.ACCESS_FINE_LOCATION" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />