安卓后保存旋转相机图像

时间:2014-01-03 04:51:50

标签: java camera

public void onClick(View v) {
    if (v == btn_camera) {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        Date date = new Date();
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

        String newPicFile = "Miuzz"+ df.format(date) + ".jpg";
        String outPath = "/sdcard/" + newPicFile;
        File outFile = new File(outPath);

        mUri = Uri.fromFile(outFile);

        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);

        startActivityForResult(cameraIntent, 1);
    }
}

我用这个来调用相机功能,然后转到另一个活动进行一些上传,但是照片的方向是错误的。我知道在保存照片后无法更改方向,其他人只会尝试通过旋转显示它并创建新的位图。

但是我要上传相机照片,如何检测相机方向并将图像保存为该方向,以便在我将图像上传到服务器后,图像将保存为正确的方向?

1 个答案:

答案 0 :(得分:1)

用于旋转返回图像的代码:

Bitmap captureBmp;
boolean image_tkn = false;
String pathToImage;
ImageUri = Uri.fromFile(image_file);
pathToImage = ImageUri.getPath();
file_path = pathToImage;
captureBmp = decodeFile(image_file);

File f = new File(file_path);
ExifInterface exif = new ExifInterface(f.getPath());
int orientation = exif.getAttributeInt(
        ExifInterface.TAG_ORIENTATION,
        ExifInterface.ORIENTATION_NORMAL);

int angle = 0;

if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
    angle = 90;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
    angle = 180;
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
    angle = 270;
}

Matrix mat = new Matrix();
mat.postRotate(angle);
Bitmap bmp = decodeFile(f);
captureBmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(),
        bmp.getHeight(), mat, true);
FileOutputStream fOut;
try {
    fOut = new FileOutputStream(f);
    captureBmp.compress(Bitmap.CompressFormat.PNG, 100, fOut);
    fOut.flush();
    fOut.close();
} catch (Exception e) {
    e.printStackTrace();
}

方法解码文件的定义

private Bitmap decodeFile(File f) {
    Bitmap b = null;
    int IMAGE_MAX_SIZE = 300;
    try {
    // Decode image size
    BitmapFactory.Options o = new BitmapFactory.Options();
    o.inJustDecodeBounds = true;

    FileInputStream fis = new FileInputStream(f);
    BitmapFactory.decodeStream(fis, null, o);
    fis.close();

    int scale = 1;
    if (o.outHeight > IMAGE_MAX_SIZE || o.outWidth > IMAGE_MAX_SIZE) {
    scale = (int) Math.pow(
            2,
            (int) Math.round(Math.log(IMAGE_MAX_SIZE
                    / (double) Math.max(o.outHeight, o.outWidth))
                    / Math.log(0.5)));
    }

    // Decode with inSampleSize
    BitmapFactory.Options o2 = new BitmapFactory.Options();
    o2.inSampleSize = scale;
    fis = new FileInputStream(f);
    b = BitmapFactory.decodeStream(fis, null, o2);
    fis.close();
    } catch (IOException e) {
    }
    return b;
}