旋转BufferedImage时出现问题 [英] Problems rotating BufferedImage

查看:412
本文介绍了旋转BufferedImage时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用AffineTransform类在Java中旋转图像时遇到一些问题。

I have some problems with rotating images in Java using the AffineTransform class.

我有以下创建图像旋转(90度)副本的方法:

I have the following method for creating a rotated (90 degrees) copy of an image:

private BufferedImage createRotatedCopy(BufferedImage img, Rotation rotation) {
    int w = img.getWidth();
    int h = img.getHeight();

    BufferedImage rot = new BufferedImage(h, w, BufferedImage.TYPE_INT_RGB);

    double theta;
    switch (rotation) {
        case CLOCKWISE:
            theta = Math.PI / 2;
            break;
        case COUNTERCLOCKWISE:
            theta = -Math.PI / 2;
            break;
        default:
            throw new AssertionError();
    }

    AffineTransform xform = AffineTransform.getRotateInstance(theta, w / 2, h / 2);
    Graphics2D g = (Graphics2D) rot.createGraphics();
    g.drawImage(img, xform, null);
    g.dispose();

    return rot;
}

旋转是一个简单的枚举,其值为NONE,CLOCKWISE和COUNTERCLOCKWISE。

Rotation is a simple enum with the values NONE, CLOCKWISE and COUNTERCLOCKWISE.

我的问题的症状显示在这里:

The symptoms of my problems are displayed here:

http://perp.se/so/rotate_problems.html

所以,轮换工作正常,但结果图像没有锚定到正确的坐标(或者应该如何放置它)。因为我真的不知道我在做什么(我的线性代数很弱),我不知道如何自己解决这个问题。

So, the rotation works OK, but the resulting images aren't anchored to the correct coordinates (or how one should put it). And since I don't really know what the heck I'm doing in the first place (my linear algebra is weak), I don't know how to solve this on my own.

我尝试了一些随机摆弄AffineTransform实例,但它没有帮助我(当然)。我已经尝试使用谷歌搜索(并搜索SO),但我见过的所有示例基本上都使用与我相同的方法...这对我不起作用。

I've tried with some random fiddling with the AffineTransform instance, but it hasn't helped me (of course). I've tried googling (and searching SO), but all examples I've seen basically use the same approach as I do... which doesn't work for me.

感谢您的建议。

推荐答案

如果必须将变换表示为单个旋转,则锚点取决于方向轮换:(w / 2,w / 2)(h / 2,h / 2)

If you must express the transform as a single rotation, the anchor point depends on the direction of rotation: Either (w/2, w/2) or (h/2, h/2).

但是表达为 translate可能更简单;旋转;翻译,例如

AffineTransform xform = new AffineTransform();
xform.translate(0.5*h, 0.5*w);
xform.rotate(theta);
xform.translate(-0.5*w, -0.5*h);

还可以考虑使用 getQuadrantRotateInstance 而不是 getRotateInstance

Also consider using getQuadrantRotateInstance instead of getRotateInstance.

这篇关于旋转BufferedImage时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆