package myj.cameratest; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import android.app.Activity; import android.app.Notification; import android.content.Intent; import android.content.pm.ActivityInfo; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.PixelFormat; import android.hardware.Camera; 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.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.View.OnTouchListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.Toast; public class CameraTest extends Activity implements SurfaceHolder.Callback{ /** Called when the activity is first created. */ private Bitmap[] bmps = new Bitmap[6]; private Camera mCamera; private ImageButton mButton,mButton1,mButton2; // private Button returnTomainmenu; private SurfaceView mSurfaceView; private SurfaceHolder holder; private AutoFocusCallback mAutoFocusCallback = new AutoFocusCallback(); private String path="CameraTest"; private Bitmap bmp = null; private int cnt=1; private int count; private boolean isFocused = false; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); /* 隐藏标题栏 */ requestWindowFeature(Window.FEATURE_NO_TITLE); /* 设定屏幕显示为横向 */ this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); setContentView(R.layout.main); Bundle bl = new Bundle(); mSurfaceView = (SurfaceView) findViewById(R.id.mSurfaceView); holder = mSurfaceView.getHolder(); holder.addCallback(CameraTest.this); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); mButton = (ImageButton)findViewById(R.id.myButton); mButton1 = (ImageButton)findViewById(R.id.myButton1); //搜索按钮(1、保存文件,读取上传) mButton2 = (ImageButton)findViewById(R.id.myButton2); //重拍按钮(放弃保存文件,并重新拍照) /* 按钮效果处理 */ mButton.setOnTouchListener(new OnTouchListener() { //@Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub // Bitmap bm; if(event.getAction() == MotionEvent.ACTION_DOWN){ //更改为按下时的背景图片 bmps[0] = BitmapFactory.decodeResource(getResources(), R.drawable.takepicture2); mButton.setImageBitmap(bmps[0]); // v.setBackgroundResource(R.drawable.barcodesearch2);//这行经测试不好使 }else if(event.getAction() == MotionEvent.ACTION_UP){ //改为抬起时的图片 bmps[1] = BitmapFactory.decodeResource(getResources(), R.drawable.takepicture); mButton.setImageBitmap(bmps[1]); // v.setBackgroundResource(R.drawable.barcodesearch); } return false; } }); mButton1.setOnTouchListener(new OnTouchListener() { //@Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub // Bitmap bm; if(event.getAction() == MotionEvent.ACTION_DOWN){ //更改为按下时的背景图片 bmps[2] = BitmapFactory.decodeResource(getResources(), R.drawable.search2); mButton1.setImageBitmap(bmps[2]); // v.setBackgroundResource(R.drawable.barcodesearch2);//这行经测试不好使 }else if(event.getAction() == MotionEvent.ACTION_UP){ //改为抬起时的图片 bmps[3] = BitmapFactory.decodeResource(getResources(), R.drawable.search); mButton1.setImageBitmap(bmps[3]); // v.setBackgroundResource(R.drawable.barcodesearch); } return false; } }); mButton2.setOnTouchListener(new OnTouchListener() { //@Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub // Bitmap bm; if(event.getAction() == MotionEvent.ACTION_DOWN){ //更改为按下时的背景图片 bmps[4] = BitmapFactory.decodeResource(getResources(), R.drawable.takepicture2); mButton2.setImageBitmap(bmps[4]); // v.setBackgroundResource(R.drawable.barcodesearch2);//这行经测试不好使 }else if(event.getAction() == MotionEvent.ACTION_UP){ //改为抬起时的图片 bmps[5] = BitmapFactory.decodeResource(getResources(), R.drawable.takepicture); mButton2.setImageBitmap(bmps[5]); // v.setBackgroundResource(R.drawable.barcodesearch); } return false; } }); /* 拍照Button的事件处理 */ mButton.setOnClickListener(new Button.OnClickListener() { //@Override public void onClick(View arg0) { /* 关闭闪光灯并拍照 */ mButton.setVisibility(View.GONE); if(bmps[0] != null && !bmps[0].isRecycled()) bmps[0].recycle(); mCamera.autoFocus(mAutoFocusCallback); // Notification notification = new Notification(); // notification.ledOffMS = 0; // notification.ledOnMS = 0; // notification.flags = notification.flags | Notification.FLAG_SHOW_LIGHTS; // takePicture(); } }); /*搜索按钮的事件处理 */ mButton1.setOnClickListener(new Button.OnClickListener() { //@Override public void onClick(View arg0) { // Bitmap newBmp = ImageTool.imageZoom(bmp, 720, 480); mButton1.setVisibility(View.GONE); mButton2.setVisibility(View.GONE); // if(bmps[2] != null && !bmps[2].isRecycled()) // bmps[2].recycle(); // if(bmps[4] != null && !bmps[4].isRecycled()) // bmps[4].recycle(); // Bitmap newBmp = null; // newBmp = bmp; // Bitmap newBmp = ImageTool.imageZoom(bmp, 960, 640); // if(!bmp.isRecycled()) // bmp.recycle(); /* 保存文件 */ if(bmp!=null) { Log.i("aaaaaaaaaaaaa", "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn"); /* 检查SDCard是否存在 */ if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { /* SD卡不存在,显示Toast信息 */ Toast.makeText(CameraTest.this,"SD卡不存在!上传失败!", Toast.LENGTH_LONG).show(); } else { try { /* 文件不存在就创建 */ File f=new File ( Environment.getExternalStorageDirectory(),path ); if(!f.exists()) { f.mkdir(); } /* 保存相片文件 */ // File n=new File(f,Constant.state + ".jpg"); // Bitmap newBmp = ImageTool.imageZoom(bmp, 720, 480); File n=new File(f,"1024_768.jpg"); FileOutputStream bos = new FileOutputStream(n.getAbsolutePath()); /* 文件转换 */ bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos); /* 调用flush()方法,更新BufferStream */ bos.flush(); /* 结束OutputStream */ bos.close(); Toast.makeText(CameraTest.this,cnt+".jpg保存成功!", Toast.LENGTH_LONG).show(); // if(!newBmp.isRecycled()) // newBmp.recycle(); // Constant.upLoadFile = "/sdcard/MyPhoto/" + Constant.state + ".jpg"; //// Constant.upLoadFile = "/sdcard/MyPhoto/3E.jpg"; // Constant.newFileName = Constant.state + ".jpg"; //// Constant.newFileName = "3E.jpg"; cnt++; } catch (Exception e) { e.printStackTrace(); } } } if(!bmp.isRecycled()) bmp.recycle(); mButton.setVisibility(View.VISIBLE); /* 重新设定Camera */ stopCamera(); initCamera(); } }); /* 重拍按钮的事件处理 */ mButton2.setOnClickListener(new Button.OnClickListener() { //@Override public void onClick(View arg0) { mButton.setVisibility(View.VISIBLE); mButton1.setVisibility(View.GONE); mButton2.setVisibility(View.GONE); /* 重新设定Camera */ // bmp = null; if(!bmp.isRecycled()) bmp.recycle(); stopCamera(); initCamera(); } }); } public void surfaceCreated(SurfaceHolder surfaceholder) { try { /* 打开相机 */ mCamera = mCamera.open(); mCamera.setPreviewDisplay(holder); } catch (IOException exception) { mCamera.release(); mCamera = null; } } public void surfaceChanged(SurfaceHolder surfaceholder, int format,int w,int h) { /* 相机初始化 */ initCamera(); count ++; Log.i("changed", count + "times"); } //@Override public void surfaceDestroyed(SurfaceHolder surfaceholder) { stopCamera(); mCamera.release(); mCamera = null; } private void takePicture() { if (mCamera != null) { mCamera.takePicture(shutterCallback, rawCallback,jpegCallback); } } private ShutterCallback shutterCallback = new ShutterCallback() { public void onShutter() { /* 按快门瞬间呼叫这里的程序 */ } }; private PictureCallback rawCallback = new PictureCallback() { public void onPictureTaken(byte[] _data, Camera _camera) { /* 要处理raw data?写?否 */ } }; private PictureCallback jpegCallback = new PictureCallback() { public void onPictureTaken(byte[] _data, Camera _camera) { /* 取得相片 */ try { /* 设定Button可视性 */ mButton.setVisibility(View.GONE); mButton1.setVisibility(View.VISIBLE); mButton2.setVisibility(View.VISIBLE); /* 取得相片Bitmap对象 */ bmp = BitmapFactory.decodeByteArray(_data, 0,_data.length); } catch (Exception e) { e.printStackTrace(); } } }; public final class AutoFocusCallback implements android.hardware.Camera.AutoFocusCallback { public void onAutoFocus(boolean focused, Camera camera) { /* 对到焦点拍照 */ if (focused) { takePicture(); } else mButton.setVisibility(View.VISIBLE); } }; /* 相机初始化的method */ private void initCamera() { if (mCamera != null) { try { Camera.Parameters parameters = mCamera.getParameters(); parameters.setPictureFormat(PixelFormat.JPEG); // parameters.setPictureSize(2560, 1920); parameters.setPictureSize(1024, 768); // parameters.setPictureSize(720, 480); mCamera.setParameters(parameters); mCamera.startPreview(); } catch (Exception e) { e.printStackTrace(); } } } /* 停止相机的method */ private void stopCamera() { if (mCamera != null) { try { /* 停止预览 */ mCamera.stopPreview(); } catch(Exception e) { e.printStackTrace(); } } } // protected void onDestroy() // { // super.onDestroy(); // for(int i = 0; i < 6; i ++) // { // if(bmps[i] != null && !bmps[i].isRecycled()) // bmps[i].recycle(); // } // Log.i("&&&&&&&&&&", "**************"); // } }
package myj.cameratest; import java.io.File; import java.io.FileOutputStream; import java.util.Calendar; import java.util.Date; import android.graphics.Bitmap; import android.graphics.Matrix; import android.os.Environment; import android.util.Log; public class ImageTool { //切割图片的一部分 public static Bitmap imageCut(Bitmap bmp, int left, int top, int right, int bottom) { Bitmap resultBmp = null; int resultWidth = right - left + 1; int resultHeight = bottom - top + 1; int colors[] = new int[resultWidth * resultHeight]; bmp.getPixels(colors, 0, resultWidth, left, top, resultWidth, resultHeight); if(bmp.isRecycled()) bmp.recycle(); resultBmp = Bitmap.createBitmap(colors, resultWidth, resultHeight, Bitmap.Config.ARGB_8888); return resultBmp; } //把图片按固定比例缩小 public static Bitmap imageZoom(Bitmap bmp, int iWidth, int iHeight) { Bitmap newBmp = null; int imageHeight = bmp.getHeight(); int imageWidth = bmp.getWidth(); float scaleW = 1; float scaleH = 1; double scalex = (float)iWidth/imageWidth; double scaley = (float)iHeight/imageHeight; scaleW = (float)(scaleW * scalex); scaleH = (float)(scaleH * scaley); Matrix matrix = new Matrix(); matrix.postScale(scaleW, scaleH); newBmp = Bitmap.createBitmap(bmp, 0, 0, imageWidth, imageHeight, matrix, true); // if(!bmp.isRecycled()) // bmp.recycle(); return newBmp; } //图片合并 public static Bitmap imageMerge(Bitmap[] bmps) { Bitmap resultBmp = null; //判断bmps中有没有值为null的bmp,有的话将其初始化为一张960*80的空白图片 int bmp_null[] = new int[960 * 80]; for(int i = 0; i < 960 * 80; i ++) bmp_null[i] = 0xffffffff; for(int i = 0; i < bmps.length; i ++) { if(bmps[i] == null) { bmps[i] = Bitmap.createBitmap(960, 80, Bitmap.Config.ARGB_8888); bmps[i].setPixels(bmp_null, 0, 960, 0, 0, 960, 80); } } int devideLineHeight = 5; int resultWidth = 0; //合并完的图像的宽度; int resultHeight = 0; //合并完的图像的高度; for(int i = 0; i < bmps.length; i ++) { if(i != (bmps.length - 1)) { if(bmps[i].getWidth() > resultWidth) resultWidth = bmps[i].getWidth(); resultHeight = resultHeight + bmps[i].getHeight() + devideLineHeight; //不同图片之间用一条宽度为5像素的红线隔开 } else { if(bmps[i].getWidth() > resultWidth) resultWidth = bmps[i].getWidth(); resultHeight = resultHeight + bmps[i].getHeight(); } } resultWidth = 960; //暂时将宽度定义为960 Log.i("Width & Height", "******* " + resultWidth + " * " + resultHeight + " ********"); //定义各图片之间分割线的像素数组 int devideLine[] = new int[resultWidth * devideLineHeight]; for(int i = 0; i < resultWidth * devideLineHeight; i ++) devideLine[i] = 0xffff0000; //生成了一张resultWidth*resultHeight的黑色图片 resultBmp = Bitmap.createBitmap(resultWidth, resultHeight, Bitmap.Config.ARGB_8888); //为了识别方便,将这张黑色图片变为纯白色 int originalColors[] = new int[resultWidth * resultHeight]; for(int i = 0; i < resultWidth * resultHeight; i ++) originalColors[i] = 0xffffffff; resultBmp.setPixels(originalColors, 0, resultWidth, 0, 0, resultWidth, resultHeight); //一张纯白色的图片 //下面的循环用图片数组中各个图片的像素数组及分割线的像素数组填充最终图片 int y = 0; int len = bmps.length; for(int i = 0; i < len; i ++) { int iWidth = bmps[i].getWidth(); int iHeight = bmps[i].getHeight(); int colors[] = new int[iWidth * iHeight]; bmps[i].getPixels(colors, 0, iWidth, 0, 0, iWidth, iHeight); if(i != (len - 1)) { resultBmp.setPixels(colors, 0, iWidth, 0, y, iWidth, iHeight); y = y + iHeight; resultBmp.setPixels(devideLine, 0, resultWidth, 0, y, resultWidth, devideLineHeight); y = y + devideLineHeight; } else { resultBmp.setPixels(colors, 0, iWidth, 0, y, iWidth, iHeight); } if(!bmps[i].isRecycled()) bmps[i].recycle(); } return resultBmp; } //保存图片 public static void saveImage(Bitmap bmp, String path, String filename, int quality) { String time = callTime(); if (bmp != null) { try { /* 文件不存在就创建 */ File f = new File(Environment.getExternalStorageDirectory(), path); if (!f.exists()) { f.mkdir(); } /* 保存相片文件 */ File n = null; // if(path.equals("MyPhoto")) // { // n = new File(f, filename + Constant.cntOfMyPhoto + ".jpg"); // Constant.cntOfMyPhoto ++; // } // else // { // n = new File(f, filename + Constant.cntOfTemp + ".jpg"); // Constant.cntOfTemp ++; // } // Constant.fileNameOfTemp = filename + Constant.cntOfTemp; n = new File(f, filename + time + ".jpg"); // Constant.fileNameOfTemp = filename + time; FileOutputStream bos = new FileOutputStream(n.getAbsolutePath()); /* 文件转换 */ bmp.compress(Bitmap.CompressFormat.JPEG, quality, bos); /* 调用flush()方法,更新BufferStream */ bos.flush(); /* 结束OutputStream */ bos.close(); // Constant.upLoadFile = "/sdcard/MyPhoto/" + filename + sTime + ".jpg"; // Constant.upLoadFile = "/sdcard/MyPhoto/" + filename + time + ".jpg"; // Constant.newFileName = filename + time + ".jpg"; } catch (Exception e) { e.printStackTrace(); } } if(!bmp.isRecycled()) bmp.recycle(); } //重置选择框的初始位置 public static void resetRect() { // Constant.left = 200; // Constant.top = 140; // Constant.right = 280; // Constant.bottom = 170; } //获取系统时间 public static String callTime() { long backTime = new Date().getTime(); Calendar cal = Calendar.getInstance(); cal.setTime(new Date(backTime)); int year = cal.get(Calendar.YEAR); int month = cal.get(Calendar.MONTH) + 1; int date = cal.get(Calendar.DAY_OF_MONTH); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); String time = "" + year + month + date + hour + minute + second; Log.i("CurrentTime", "^^^^^^^^^^^^^" + time + "^^^^^^^^^^^^^"); return time; // return date + 100 * (month + 1) + 10000 * year; } }
<uses-permission android:name="android.permission.CAMERA" /> <uses-feature android:name="android.hardware.camera" /> <uses-feature android:name="android.hardware.camera.autofocus" />