Android-从前置摄像头拍摄照片会旋转照片

时间:2012-10-12 06:18:39

标签: android android-camera

我正在Android中创建一个应用程序,用户只能在纵向模式下从前置摄像头拍摄照片。我已经将相机视图固定为纵向,但是当拍摄照片时,它显示为旋转。最糟糕的是,不同手机的旋转方向不同,一部手机右转,而另一部手机左转。

这是我的代码片段

确保活动仅以肖像方式播放

 <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" 
             android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

获取相机

   @Override
  public void onResume() {
    super.onResume();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
      Camera.CameraInfo info=new Camera.CameraInfo();

      for (int i=0; i < Camera.getNumberOfCameras(); i++) {
        Camera.getCameraInfo(i, info);

        if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
          camera=Camera.open(i);
        }
      }
    }

    if (camera == null) {
      camera=Camera.open();
    }
  }

旋转相机

    @Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    if(previewing){
        camera.stopPreview();
        previewing = false;
    }

    if (camera != null){
        try {
            camera.setPreviewDisplay(surfaceHolder);
            camera.setDisplayOrientation(90);
            initPreview(width, height);
            startPreview();

            previewing = true;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

拍摄照片

     PictureCallback myPictureCallback_JPG = new PictureCallback(){

    @Override

     public void onPictureTaken(byte[] data, Camera arg1) {
         // new SavePhotoTask().execute(data);
        Intent myIntent = new Intent(MainActivity.this, CropActivity.class);
        Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
        myIntent.putExtra("image", bitmap);
        MainActivity.this.startActivity(myIntent);

     }};

BMP发送总是以旋转形式出现,但并不总是以90度出现。看起来android 4.0不仅可以旋转,还可以翻转图像。有没有一种很好的方法来检测并确保我总能得到正确的图片?

1 个答案:

答案 0 :(得分:28)

镜像和翻转的问题被认为是特定于android 4.0+,所以这有效

Matrix rotateRight = new Matrix();
rotateRight.preRotate(90);

if(android.os.Build.VERSION.SDK_INT>13 && CameraActivity.frontCamera)
{
    float[] mirrorY = { -1, 0, 0, 0, 1, 0, 0, 0, 1};
    rotateRight = new Matrix();
    Matrix matrixMirrorY = new Matrix();
    matrixMirrorY.setValues(mirrorY);

    rotateRight.postConcat(matrixMirrorY);

    rotateRight.preRotate(270);

}

final Bitmap rImg= Bitmap.createBitmap(img, 0, 0,
                img.getWidth(), img.getHeight(), rotateRight, true);