6

我正在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 不仅旋转而且翻转图像。有没有一种很好的方法来检测并确保我总是得到正确的图片?

4

1 回答 1

30

镜像和翻转的问题被认为是 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);
于 2012-10-16T11:32:50.240 回答