根据需求,一般分为预览时竖直和拍照后得到竖直方向的照片


情况一、拍照时竖直预览:


实现原理①:设置拍照的Activity为横屏

实现①:在AndroidManifest.xml相应的activity添加一句android:screenOrientation="landscape"

缺点:Activity设置为横屏之后,上面的按钮等相应的也会旋转。


实现原理②:设置预览效果为竖直方向

实现②:在Camera对象初始化之后,设置Camera对象为竖直预览

代码:

private void setDisplayOrientation(){int rotation = getWindowManager()           .getDefaultDisplay().getRotation();int degree = 0;switch (rotation) {case Surface.ROTATION_0:degree = 0; break;case Surface.ROTATION_90:degree = 90; break;case Surface.ROTATION_180:degree = 180; break;case Surface.ROTATION_270:degree = 270; break;}int result;CameraInfo info = new CameraInfo();Camera.getCameraInfo(0, info);if(info.facing == CameraInfo.CAMERA_FACING_FRONT){result = (info.orientation + degree) % 360;result = (360 - result) % 360;}else{result =(info.orientation - degree + 360 ) % 360;}myCamera.setDisplayOrientation(result);//这里的myCamera就是已经初始化的Camera对象}



情况二、得到竖直方向的照片:

实现原理:将拍照回调函数得到的Byte[]数组转化为BitMap对象,再对BitMap对象进行旋转处理

实现:贴上源代码吧

@Overridepublic void onPictureTaken(byte[] data, Camera camera) {//将得到的照片进行270°旋转(旋转角度可以自己修改),使其竖直Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);Matrix matrix = new Matrix();matrix.preRotate(270);bitmap = Bitmap.createBitmap(bitmap ,0,0, bitmap .getWidth(), bitmap .getHeight(),matrix,true);};


如果需要修改图片的宽高:

我们都知道手机拍下来的照片长和宽都有一个默认值(我的手机的是640 * 480),那么如果用户需要修改长宽比例,需要通过Matrix对象的postScale方法重新设置长宽比例。接着用这个Matrix对象重新创建Bitmap对象。

代码(在上一部分代码里添加一些内容就好):

@Overridepublic void onPictureTaken(byte[] data, Camera camera) {//完成拍照后关闭ActivityCameraActivity.this.finish();//将得到的照片进行缩放及旋转(旋转角度自己可以定),使其竖直Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);Matrix matrix = new Matrix();int width = bitmap.getWidth();int height = bitmap.getHeight();//定义新图片的宽和高(默认的好像是 640 * 480)int newWidth = 1080;int newheight = 1920;//得到缩放比例(float类型)float widthScale = (float) newWidth / width;float heightScale = (float) newheight / height;//设置缩放比例matrix.postScale(widthScale, heightScale);//设置旋转角度(如果只做缩放处理,旋转这一步可以不要)matrix.preRotate(270);bitmap = Bitmap.createBitmap(bitmap ,0,0, width, height,matrix,true);}


如果需要将BitMap存储到本地SD卡

代码:

//创建并保存图片文件File pictureFile = new File("/sdcard/", "camera.jpg");try {FileOutputStream fos = new FileOutputStream(pictureFile);bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);fos.close();} catch (Exception error) {error.printStackTrace();}


更多相关文章

  1. Android(安卓)自定义适配器逐步优化
  2. Android消息处理机制——Looper、Handler、Message 源码分析
  3. android GC内存泄露问题
  4. Android:WebView全面总结
  5. 基于android的Socket通信
  6. Android操作JNI函数以及复杂对象传递
  7. Android(安卓)源码解析Handler处理机制(一)
  8. Android内存的全面分析-让你吃透
  9. android源码解析(十七)-->Activity布局加载流程

随机推荐

  1. Android串口开发初体验(windows开发环境)
  2. Android音频采集
  3. Android中的线程机制(Handler Looper)(二)
  4. android 项目中使用到的网络请求框架以及
  5. 史上最强Android保活思路:深入剖析腾讯TIM
  6. Android:分析onXXX事件监听器中的两个参数
  7. Android跳转系统界面_大全集
  8. 【博主已解决】Android(安卓)Studio3.6/4
  9. 【移动开发】Android图片异步加载之Andro
  10. Android中读取系统图库(包含相册)中的图片,