从Android相机旋转图片

时间:2013-08-20 12:16:37

标签: android camera orientation android-camera

我正在为相机设置旋转:

stopPreview();
Camera.Parameters p = mCamera.getParameters();
p.setRotation(90);
mCamera.setParameters(p);
startPreview();

设备处于水平方向时拍摄照片。我需要将照片旋转到垂直方向。但是,当我保存jpeg它永远不会旋转时,它总是水平的。

protected void onJpegPicture(byte[] data, int width, int height) {
    saveJpeg(data, file);
}

我错过了什么吗?我不认为我应该在拍摄后手动旋转照片。我认为相机应该可以为我做这件事。

setRotation参数并不重要。我尝试了所有可能的值(0,90,180,270)。

3 个答案:

答案 0 :(得分:3)

您应该使用的代码片段,假设您在调用takePicture()之前调用setParameters()。您可以尝试在takePicture调用之前设置参数,而不是在开始预览之前设置参数,但这不重要。

请注意,您可能不想在这里使用90,因为图片的方向是相对于传感器的方向而不是您当前的UI方向确定的。传感器是否与纵向或横向对齐取决于您的设备 - 您可以使用CameraInfo.orientation进行检查。但是,如果您尝试了所有旋转值,则会看到效果。

您在哪些设备上看到此行为?另外,您如何查看最终图像?一些图像查看器仍然无法正确解释JPEG旋转字段,但任何设备上的图库应用程序确实应该(特别是如果它是默认应用程序)。

答案 1 :(得分:2)

尝试旋转相机及其预览。即。

//rotate preview
camera.setDisplayOrientation(90);
//rotate camera
Camera.Parameters p = camera.getParameters();
p.setRotation(90);
camera.setParameters(p);

在多个HTC设备上测试过它。

答案 2 :(得分:0)

使用此方法传递Image本身以及您案例中为90的rotation degree

public static Image rotate(Image img, double angle){
    double sin = Math.abs(Math.sin(Math.toRadians(angle))), cos = Math.abs(Math.cos(Math.toRadians(angle)));
    int w = img.getWidth(null), h = img.getHeight(null);
    int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math.floor(h
        * cos + w * sin);
    BufferedImage bimg = toBufferedImage(getEmptyImage(neww, newh));
    Graphics2D g = bimg.createGraphics();
    g.translate((neww - w) / 2, (newh - h) / 2);
    g.rotate(Math.toRadians(angle), w / 2, h / 2);
    g.drawRenderedImage(toBufferedImage(img), null);
    g.dispose();
    return toImage(bimg);
}