您的位置:首页 > 编程语言 > Java开发

文章标题

2017-06-01 21:39 190 查看

CameraActivity..java

package org.xm.camerasimple;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class CameraActivity extends Activity {

public static final String TAG = "CameraSimple";
private Camera mCamera;
private CameraPreview mPreview;
private FrameLayout mCameralayout;
private ImageView mTakePictureBtn;
private ImageView mSwitchCameraBtn;
private int mCameraId = CameraInfo.CAMERA_FACING_BACK;

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

// 设置无标题
requestWindowFeature(Window.FEATURE_NO_TITLE);
// 设置全屏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

setContentView(R.layout.activity_camera);

if (!checkCameraHardware(this)) {
Toast.makeText(CameraActivity.this, "相机不支持", Toast.LENGTH_SHORT)
.show();
} else {
openCamera();
initView();
setCameraDisplayOrientation(this, mCameraId, mCamera);
}

}

private void initView() {
mTakePictureBtn = (ImageView) findViewById(R.id.btn_capture);
mTakePictureBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mCamera.autoFocus(mAutoFocusCallback);
}
});
mSwitchCameraBtn = (ImageView) findViewById(R.id.btn_switch_camera);
mSwitchCameraBtn.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
switchCamera();
}
});
}

// 判断相机是否支持
private boolean checkCameraHardware(Context context) {
if (context.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA)) {
return true;
} else {
return false;
}
}

// 获取相机实例
public Camera getCameraInstance() {
Camera c = null;
try {
c = Camera.open(mCameraId);
} catch (Exception e) {
e.printStackTrace();
}
return c;
}

// 开始预览相机
public void openCamera() {
if (mCamera == null) {
mCamera = getCameraInstance();
mPreview = new CameraPreview(CameraActivity.this, mCamera);
mPreview.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
mCamera.autoFocus(null);
return false;
}
});
mCameralayout = (FrameLayout) findViewById(R.id.camera_preview);
mCameralayout.addView(mPreview);
mCamera.startPreview();
}
}

// 释放相机
public void releaseCamera() {
if (mCamera != null) {
mCamera.setPreviewCallback(null);
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
}

// 拍照回调
private PictureCallback mPictureCallback = new PictureCallback() {
@Override
public void onPictureTaken(final byte[] data, Camera camera) {
File pictureDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

//final String picturePath = pictureDir
//      + File.separator
//      + new DateFormat().format("yyyyMMddHHmmss", new Date())
//              .toString() + ".jpg";
final String picturePath = getFilesDir().getPath()+File.separator+System.currentTimeMillis()+".jpg";
final int cameraid = mCameraId;
new Thread(new Runnable() {
@Override
public void run() {

File file = new File(picturePath);
try {
// 获取当前旋转角度, 并旋转图片
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);
if (cameraid == CameraInfo.CAMERA_FACING_BACK) {
bitmap = rotateBitmapByDegree(bitmap, 90);
} else {
bitmap = rotateBitmapByDegree(bitmap, -90);
}
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
bitmap.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}).start();

mCamera.startPreview();
}
};

// 旋转图片
public static Bitmap rotateBitmapByDegree(Bitmap bm, int degree) {
Bitmap returnBm = null;
Matrix matrix = new Matrix();
matrix.postRotate(degree);
try {
returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
bm.getHeight(), matrix, true);
} catch (OutOfMemoryError e) {
}
if (returnBm == null) {
returnBm = bm;
}
if (bm != returnBm) {
bm.recycle();
}
return returnBm;
}

// 设置相机横竖屏
public void setCameraDisplayOrientation(Activity activity, int cameraId,
Camera camera) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay()
.getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}

int result;
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360;
} else {
result = (info.orientation - degrees + 360) % 360;
}
camera.setDisplayOrientation(result);
}

// 切换前置和后置摄像头
public void switchCamera() {
CameraInfo cameraInfo = new CameraInfo();
Camera.getCameraInfo(mCameraId, cameraInfo);
if (cameraInfo.facing == CameraInfo.CAMERA_FACING_BACK) {
mCameraId = CameraInfo.CAMERA_FACING_FRONT;
} else {
mCameraId = CameraInfo.CAMERA_FACING_BACK;
}
mCameralayout.removeView(mPreview);
releaseCamera();
openCamera();
setCameraDisplayOrientation(CameraActivity.this, mCameraId, mCamera);
}

// 聚焦回调
private AutoFocusCallback mAutoFocusCallback = new AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
if (success) {
mCamera.takePicture(null, null, mPictureCallback);
}
}
};
}


CameraPreview.java

package org.xm.camerasimple;
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);
}

public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
e.printStackTrace();
}
}

public void surfaceDestroyed(SurfaceHolder holder) {
}

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

try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
} catch (Exception e) {
e.printStackTrace();
}
}

}


xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<FrameLayout
android:id="@+id/camera_preview"
android:layout_width="match_parent"
android:layout_height="match_parent" />

<ImageView
android:id="@+id/btn_capture"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_margin="10dp"
android:src="@drawable/selector_picture" />

<ImageView
android:id="@+id/btn_switch_camera"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_margin="10dp"
android:src="@drawable/selector_switch_camera" />

</RelativeLayout>


selector_picture

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/ic_picture_pressed" android:state_pressed="true"></item>
<item android:drawable="@drawable/ic_picture" android:state_pressed="false"></item>

</selector>


selector_switch_camera

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/ic_switch_camera" android:state_pressed="false"></item>
<item android:drawable="@drawable/ic_switch_camera_pressed" android:state_pressed="true"></item>

</selector>








内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java