用Java旋转bufferedimage

问题描述 投票:0回答:1

我已经在Java中编写了一个图像旋转方法(允许旋转为90度,180度和270度),但它似乎没有按预期工作。我显然做错了什么,但我完全无法弄清楚是什么。关于输出的问题是图像确实是旋转的,但是图像有黑色部分,就像图像不在正确的位置一样。

我的第一次尝试是在没有结果变量的情况下使用它作为目的地,相反,我这样做:

return affineTransformOp.filter(bufferedImage, null);

旋转很好,图像没有黑色部分,但颜色很奇怪,如果某些颜色改变,皮肤颜色变红。所以当我看到其他人遇到同样的问题时,我已经改变了它。

这就是我现在所拥有的:

private BufferedImage rotateImage(ImageData imageData, BufferedImage bufferedImage) {
    AffineTransform affineTransform = new AffineTransform();

    affineTransform.rotate(imageData.getRotation().getRotationAngle(), bufferedImage.getWidth() / 2, bufferedImage.getHeight() / 2);

    AffineTransformOp affineTransformOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_BILINEAR);

    BufferedImage result = new BufferedImage(bufferedImage.getHeight(), bufferedImage.getWidth(), bufferedImage.getType());

    affineTransformOp.filter(bufferedImage, result);

    return result;
}

我也试过翻译图像,但它并没有多大帮助。

我真的很感激任何帮助。谢谢。

java rotation bufferedimage affinetransform
1个回答
0
投票

如果将来有人遇到同样的问题,请找到答案。

这是修改后的Java方法解决了我的问题:

private BufferedImage rotateImage(ImageRotation imageRotation, BufferedImage bufferedImage) {
    AffineTransform affineTransform = new AffineTransform();

    if (ImageRotation.ROTATION_90.equals(imageRotation) || ImageRotation.ROTATION_270.equals(imageRotation)) {
        affineTransform.translate(bufferedImage.getHeight() / 2, bufferedImage.getWidth() / 2);
        affineTransform.rotate(imageRotation.getRotationAngle());
        affineTransform.translate(-bufferedImage.getWidth() / 2, -bufferedImage.getHeight() / 2);

    } else if (ImageRotation.ROTATION_180.equals(imageRotation)) {
        affineTransform.translate(bufferedImage.getWidth() / 2, bufferedImage.getHeight() / 2);
        affineTransform.rotate(imageRotation.getRotationAngle());
        affineTransform.translate(-bufferedImage.getWidth() / 2, -bufferedImage.getHeight() / 2);

    } else {
        affineTransform.rotate(imageRotation.getRotationAngle());
    }

    AffineTransformOp affineTransformOp = new AffineTransformOp(affineTransform, AffineTransformOp.TYPE_BILINEAR);

    BufferedImage result;

    if (ImageRotation.ROTATION_90.equals(imageRotation) || ImageRotation.ROTATION_270.equals(imageRotation)) {
        result = new BufferedImage(bufferedImage.getHeight(), bufferedImage.getWidth(), bufferedImage.getType());

    } else {
        result = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), bufferedImage.getType());
    }

    affineTransformOp.filter(bufferedImage, result);

    return result;
}
© www.soinside.com 2019 - 2024. All rights reserved.