拍照用的activity
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 com.lefu.utils.ConstantUtils;
import com.lefu.utils.ImageUtils;
import com.lefu.view.CameraSurfacePreview;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.FeatureInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
public class AndroidCameraActivity extends Activity implements OnClickListener, PictureCallback {
private CameraSurfacePreview mCameraSurPreview = null;
private Button mCaptureButton = null;
private String TAG = "Dennis";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_camera);
// Create our Preview view and set it as the content of our activity.
FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
mCameraSurPreview = new CameraSurfacePreview(this);
preview.addView(mCameraSurPreview);
// Add a listener to the Capture button
mCaptureButton = (Button) findViewById(R.id.button_capture);
mCaptureButton.setOnClickListener(this);
}
@Override
public void onPictureTaken(byte[] data, Camera camera) {
//save the picture to sdcard
final File pictureFile = getOutputMediaFile();
if (pictureFile == null){
Log.d(TAG, "Error creating media file, check storage permissions: ");
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
//ImageUtils.setRoateImage(pictureFile.getAbsolutePath());
Bitmap bitmap=BitmapFactory.decodeFile(pictureFile.getAbsolutePath());
//由于竖屏拍照拍完后实际图片翻转了90度,所以这里翻转90度,让图片变正
bitmap= ImageUtils.rotaingImageView(90, bitmap);
//这里是把图片进行压缩保存
ImageUtils.saveMyBitmap(pictureFile.getAbsolutePath(), bitmap);
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
// Restart the preview and re-enable the shutter button so that we can take another picture
camera.startPreview();
//See if need to enable or not
mCaptureButton.setEnabled(true);
//把图片回传到上一个Activity
Intent intent=new Intent(); intent.putExtra("imagepath",pictureFile.getAbsolutePath();
setResult(1, intent);
finish();
}
@Override
public void onClick(View v) {
mCaptureButton.setEnabled(false);
// get an image from the camera
mCameraSurPreview.takePicture(this);
}
private File getOutputMediaFile(){
//get the mobile Pictures directory
// File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File picDir =new File(ConstantUtils.PICFILE);
if(!picDir.exists()){
picDir.mkdirs();
}
//get the current time
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
return new File(picDir,timeStamp + ".jpg");
}
}
CameraSurfacePreview类,用来照图片的
import java.io.IOException;
import java.util.List;
import com.lefu.utils.LogUtil;
import android.content.Context;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class CameraSurfacePreview extends SurfaceView implements
SurfaceHolder.Callback {
private SurfaceHolder mHolder;
private Camera mCamera;
public CameraSurfacePreview(Context context) {
super(context);
mHolder = getHolder();
mHolder.addCallback(this);
// deprecated setting, but required on Android versions prior to 3.0
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d("Dennis", "surfaceCreated() is called");
try {
// 对相机进行初始化
mCamera = Camera.open();
mCamera.setPreviewDisplay(holder);
mCamera.setDisplayOrientation(90);
//得到手机设备支持的所有分辨率格式,返回的是一个list
Camera.Parameters parameters = mCamera.getParameters();
List<Size> list = parameters.getSupportedPictureSizes();
Camera.Size size = null;
int siepos=0;
//因为返回的list可能是从小到大排列,也有可能是从大到小排列,这里进行 了判断,我选择的是相对较小的分辨率,如果分辨率太大,容易溢出
if (list.get(0).width < list.get(list.size() -1).width) {
//size = list.get(0);
if(list.size()>=5){
siepos=3;
}else{
siepos=(list.size())/2;
}
} else {
//size = list.get(list.size() - 1);
if(list.size()>=5){
siepos=list.size()-4;
}else{
siepos=(list.size())/2;
}
}
// int pos=(list.size())/2;
size=list.get(siepos);
LogUtil.i("this.getResources().getConfiguration().orientation ", this.getResources().getConfiguration().orientation+"");
LogUtil.i("size.width", size.width+"");
LogUtil.i("size.height", size.height+"");
//设置相机的分辨率
parameters.setPictureSize(size.width, size.height);
mCamera.setParameters(parameters);
} catch (Exception e) {
Log.d("Dennis", "Error setting camera preview: " + e.getMessage());
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// 已经获得Surface的width和height,设置Camera的参数
Log.d("Dennis", "surfaceChanged() is called");
try {
mCamera.startPreview();
} catch (Exception e) {
Log.d("Dennis", "Error starting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
if (mCamera != null) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
Log.d("Dennis", "surfaceDestroyed() is called");
}
public void takePicture(PictureCallback imageCallback) {
mCamera.takePicture(null, null, imageCallback);
}
}
ImageUtil类进行图片压缩保存
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
public class ImageUtils {
public static void setRoateImage(String filepath){
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmapOptions.inSampleSize = 8;
File file = new File(filepath);
/**
* 获取图片的旋转角度,有些系统把拍照的图片旋转了,有的没有旋转
*/
int degree = readPictureDegree(file.getAbsolutePath());
Bitmap cameraBitmap = BitmapFactory.decodeFile(filepath, bitmapOptions);
bitmap = cameraBitmap;
/**
* 把图片旋转为正的方向
*/
bitmap = rotaingImageView(degree, bitmap);
}
/**
* 读取图片属性:旋转的角度
* @param path 图片绝对路径
* @return degree旋转的角度
*/
public static int readPictureDegree(String path) {
int degree = 0;
try {
ExifInterface exifInterface = new ExifInterface(path);
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
degree = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
degree = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
degree = 270;
break;
}
} catch (IOException e) {
e.printStackTrace();
}
return degree;
}
/**
* 旋转图片
* @param angle
* @param bitmap
* @return Bitmap
*/
public static Bitmap rotaingImageView(int angle , Bitmap bitmap) {
//旋转图片 动作
Matrix matrix = new Matrix();;
matrix.postRotate(angle);
System.out.println("angle2=" + angle);
// 创建新的图片
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
return resizedBitmap;
}
public static void saveMyBitmap(String filepath,Bitmap mBitmap){
File f = new File(filepath);
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
LogUtil.e("在保存图片时出错:",e.toString());
}
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
try {
fOut.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
布局文件:
<?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:orientation="vertical" >
<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:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
style="@style/substyle"
android:layout_marginBottom="10dp"
android:text="拍照" />
</LinearLayout>