最近搞了一个自定义相机的,可以镜像的相机。图就不上了,大概就是按一下等五秒就拍个照
package com.lzj.pl.hysteria.ui.main.activity.sort;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.SurfaceTexture;
import android.hardware.Camera;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.TextureView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.lzj.pl.hysteria.R;
import com.lzj.pl.hysteria.utils.Config;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 自定义相机
*/
@SuppressLint({"NewApi", "SdCardPath"})
public class CameraActivity extends Activity implements Runnable, View.OnClickListener {
// 预览图片范围
private TextureView surfaceView;
private TextView tv_time;
// 倒计时拍摄
private int cameratime = 5;
private Camera camera;
private boolean preview = false;
// 文件名字
private String filename;
// 文件名字的带的时间戳
private String timeString;
// 格式化时间
private SimpleDateFormat dateFormat;
// 日期对象
private Date date;
// 控制线程
boolean stopThread = false;
boolean canTake = true;
private ImageView start_came;
private ImageView delet_came;// = findViewById(R.id.delet_came);
private ImageView chouse_came;
private ImageView image_close;
private File file;
String photo;
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
int what = msg.what;
switch (what) {
case 222:
tv_time.setText("" + cameratime);
if ("0".equals(tv_time.getText().toString())) {
tv_time.setText("");
takePhoto();
cameratime = 5;
start_came.setVisibility(View.GONE);
}
break;
}
}
;
};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
CameraActivity.this.setFinishOnTouchOutside(false);
// 初始化数据
findView();
surfaceView.setSurfaceTextureListener(new SufaceListener());
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
// 开启线程
}
private final class SufaceListener implements TextureView.SurfaceTextureListener {
@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface,
int width, int height) {
// surfaceView = surface;
//初始化、预览Camera
Matrix matrix = surfaceView.getTransform(new Matrix());
matrix.setScale(-1, 1);
int width1 = surfaceView.getWidth();
int h1 = surfaceView.getHeight();
matrix.postTranslate(width1, 0);
surfaceView.setTransform(matrix);
try {
for (int i = 0; i < Camera.getNumberOfCameras(); i++) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(i, info);
// 调用系统的前置摄像头
if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
camera = Camera.open(i);
}
}
Camera.Parameters parameters = camera.getParameters();
/* 每秒从摄像头捕获5帧画面, */
parameters.setPreviewFrameRate(5);
/* 设置照片的输出格式:jpg */
parameters.setPictureFormat(PixelFormat.JPEG);
/* 照片质量 */
parameters.set("jpeg-quality", 100);
WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
camera.setParameters(parameters);
// camera.setDisplayOrientation(360);
camera.setPreviewTexture(surface);// 通过SurfaceView显示取景画面
camera.startPreview();
preview = true;
} catch (Exception e) {
//
//
}
}
@Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
//关闭、释放Camera资源
if(null != camera){
if(preview){
camera.stopPreview();
}
camera.release();
camera = null;
}
return true;
}
@Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface,
int width, int height) {
}
@Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
// TODO Auto-generated method stub
}
}
/**
* 拍摄照片
*/
private void takePhoto() {
// 执行拍照效果
camera.takePicture(null, null, new Camera.PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
try {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
data.length);
timeString = formatDate();
//保存到data/data目录自定义文件夹下
File dirFile = new File(Config.PHOTO_PATH);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
filename = Config.PHOTO_PATH
+ "photo.jpg";
File file = new File(filename);
boolean createNewFile = file.createNewFile();
System.out.println("创建文件夹成功没有" + createNewFile);
System.out.println(file);
FileOutputStream outStream = new FileOutputStream(file);
// bitmap = rotaingImageView(readPictureDegree(filename),bitmap);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, outStream);
outStream.flush();
outStream.close();
delet_came.setVisibility(View.VISIBLE);
chouse_came.setVisibility(View.VISIBLE);
// 重新浏览
// camera.stopPreview();
// camera.startPreview();
preview = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
});
}
@Override
public void run() {
while (!stopThread) {
try {
//按秒数倒计时
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cameratime--;
mHandler.sendEmptyMessage(222);
if (cameratime <= 0) {
break;
}
}
}
// 初始化数据
private void findView() {
surfaceView = this.findViewById(R.id.surfaceView);
start_came = findViewById(R.id.start_came);
delet_came = findViewById(R.id.delet_came);
chouse_came = findViewById(R.id.chouse_came);
tv_time = (TextView) findViewById(R.id.tv_time);
image_close = findViewById(R.id.image_close);
image_close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
start_came.setOnClickListener(this);
delet_came.setOnClickListener(this);
chouse_came.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.start_came:
if (!canTake)
return;
canTake = false;
tv_time.setText("" + cameratime);
new Thread(this).start();
break;
case R.id.delet_came:
canTake = true;
camera.startPreview();
delet_came.setVisibility(View.GONE);
start_came.setVisibility(View.VISIBLE);
chouse_came.setVisibility(View.GONE);
break;
case R.id.chouse_came:
Intent intent = new Intent();
intent.setData(Uri.fromFile(new File(filename)));
// setResult(UserFragment.PHOTO_REQUEST, intent);
finish();
break;
}
}
public Uri getImageContentUri(Context context, java.io.File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
new String[]{filePath}, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
// 格式化系统的时间
public String formatDate() {
date = new Date(System.currentTimeMillis());
// 日期格式
dateFormat = new SimpleDateFormat("'IMG'_yyyyMMddHHmmss");
return dateFormat.format(date);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
// 线程已关闭
super.onDestroy();
stopThread = true;
}
}
布局
<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"
android:background="#000000"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerInParent="true"
android:orientation="vertical">
<TextureView
android:id="@+id/surfaceView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="40dp"
android:layout_weight="1"
/>
<RelativeLayout
android:layout_width="match_parent"
android:paddingTop="50dp"
android:layout_height="200dp"
android:background="#000000">
<ImageView
android:id="@+id/start_came"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:src="@mipmap/xj" />
<ImageView
android:id="@+id/chouse_came"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_centerHorizontal="true"
android:layout_marginRight="350dp"
android:layout_marginBottom="20dp"
android:src="@mipmap/xz"
android:visibility="gone" />
<ImageView
android:id="@+id/delet_came"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginLeft="350dp"
android:layout_marginBottom="20dp"
android:src="@mipmap/sc"
android:visibility="gone" />
</RelativeLayout>
</LinearLayout>
<ImageView
android:id="@+id/image_close"
android:layout_width="60dp"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginTop="30dp"
android:layout_marginRight="30dp"
android:src="@mipmap/finsh" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="请调整位置到此区域"
android:textColor="#ff0000"
android:textSize="32sp"
android:visibility="gone" />
<TextView
android:id="@+id/tv_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:paddingTop="10dp"
android:text=""
android:textColor="#ffffff"
android:textSize="168sp"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
config文件
package com.lzj.pl.hysteria.utils;
import android.os.Environment;
/**
* Created by LS on 2018/3/17.
*/
public class Config {
//上线重置 并且设置HttpUtils 和SpalshAct测试代码 LogActivity
//ResponseHandler 修改 UrlConstants
public static final boolean DEBUG = true;
public static final long PULL_DOWN_REFRESH_DELAY = 100;
public static final long PULL_DOWN_REFRESH_DELAY_1500 = 1000;
public static final String PHOTO_AUTHORITY = "com.example.tv.provider";
public static final String PHOTO_PATH = Environment.getExternalStorageDirectory() + "/"
+ "av" + "/photos/";
public static final String IMAGE_PATH = Environment.getExternalStorageDirectory() + "/"
+ "tv" + "/images/";
public static final String WECHAT_APPID = "wxb4ae2ac65a682266";
public static final String VIDEO_PATH = Environment.getExternalStorageDirectory() + "/"
+"tv" + "/video/";
public static String apiKey = "替换为你的apiKey(ak)";
public static String secretKey = "替换为你的secretKey(sk)";
public static String licenseID = "FaceFaceFaceFace-face-android";
public static String licenseFileName = "替换为你的license文件";
}