簡體   English   中英

Android:如何為相機拍攝的圖像設置方向?

[英]Android: how to set orientation for an image taken by camera?

我寫了這段代碼:

private File imageFile;

private void addButtonListener(){
    Button btn = (Button)findViewById(R.id.Button);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            File pictureDictionary = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            imageFile = new File(pictureDictionary, "myImage");
            Intent i = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            i.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imageFile));
            startActivityForResult(i, 0);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if(requestCode == 0){
        Bitmap photo = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
        if(photo!=null) {
            ImageView view = (ImageView)findViewById(R.id.ImageView);
            view.setImageBitmap(photo);
        }
    }
}

當我在Galaxy s5上運行它並嘗試拍攝人像照片時,它將顯示旋轉90度的照片。 當我嘗試拍攝風景照片時,應用程序崩潰了。

第一步:從圖像獲取方向

private Matrix getOrientationMatrix(String path) {
    Matrix matrix = new Matrix();
    ExifInterface exif;
    try {
        exif = new ExifInterface(path);
        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

        switch (orientation) {
        case ExifInterface.ORIENTATION_FLIP_HORIZONTAL:
            matrix.setScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            matrix.setRotate(180);
            break;
        case ExifInterface.ORIENTATION_FLIP_VERTICAL:
            matrix.setRotate(180);
            matrix.postScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_TRANSPOSE:
            matrix.setRotate(90);
            matrix.postScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_ROTATE_90:
            matrix.setRotate(90);
            break;
        case ExifInterface.ORIENTATION_TRANSVERSE:
            matrix.setRotate(-90);
            matrix.postScale(-1, 1);
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            matrix.setRotate(-90);
            break;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }


   return matrix;
}

第二步:旋轉位圖跟隨方向

b = Bitmap.createBitmap(photo , 0, 0, outWidth, outHeight, getOrientationMatrix(path), true);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM