根据需求,一般分为预览时竖直和拍照后得到竖直方向的照片
情况一、拍照时竖直预览:
实现原理①:设置拍照的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对象进行旋转处理
实现:贴上源代码吧
@Override
public 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对象。
代码(在上一部分代码里添加一些内容就好):
@Override
public void onPictureTaken(byte[] data, Camera camera) {
//完成拍照后关闭Activity
CameraActivity.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();
}