如何在保存之前在Android相机预览应用中旋转图像?

时间:2015-01-05 00:41:35

标签: android android-camera

我有一个Android摄像头应用程序,以肖像模式拍照,相机预览很好......但是当我拍照时它保存在横向模式...它旋转90度:我的代码onPictureTaken():< / p>

PictureCallback jpegCallback = new PictureCallback() {
    @Override
    public void onPictureTaken(byte[] arg0, Camera arg1) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
        String date = dateFormat.format(new Date());
        String photoFile = "Picture_" + date + ".jpg";

        String filename = pictureFileDir.getPath() + File.separator
                + photoFile;

        Log.e("path", filename.toString());

        File pictureFile = new File(filename);

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(arg0);
            fos.close();

            Bitmap bm = BitmapFactory.decodeFile(filename);
            ByteArrayOutputStream bao = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG, 90, bao);
            byte[] ba = bao.toByteArray();
            // sba1 = Base64.encodeBytes(ba);
            int flag = 0; // you can pass the default 0 = Base64.DEFAULT
            String ba1 = Base64.encodeToString(ba, flag);

            // Log.e("base64", "-----" + ba1);

            Toast.makeText(AndroidCamera.this,
                    "New Image saved 22222:" + photoFile, Toast.LENGTH_LONG)
                    .show();
            Intent intent = new Intent(AndroidCamera.this,
                    UploadActivity.class);

            fileUri = Uri.fromFile(pictureFile);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

            // start the image capture Intent
            startActivityForResult(intent,
                    CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
            launchUploadActivity(true);

        } catch (Exception error) {
            // Log.d(MakePhotoActivity.DEBUG_TAG, "File" + filename +
            // "not saved: "
            // + error.getMessage());
            Toast.makeText(AndroidCamera.this, "Image could not be saved.",
                    Toast.LENGTH_LONG).show();
        }
    }
};

1 个答案:

答案 0 :(得分:2)

您可以将位图旋转90度,如下所示:

Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

在您的具体示例中,您需要将其保存回原始路径:

Bitmap bm = BitmapFactory.decodeFile(filename);

Matrix matrix = new Matrix();
matrix.postRotate(90);    
Bitmap rotatedBitmap = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, true);

FileOutputStream fos = new FileOutputStream(pictureFile);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();

您也可以使用Camera.Parameters.setRotation()