Java:旋转图像

Jim*_*mmt 16 java swing image rotation graphics2d

我需要能够单独旋转图像(在java中).到目前为止我唯一发现的是g2d.drawImage(image,affinetransform,ImageObserver).不幸的是,我需要在特定的点绘制图像,并且没有一个方法可以分别对图像进行旋转,并且2.允许我设置x和y.任何帮助表示赞赏

Ala*_*ter 30

这就是你如何做到的.此代码假定存在称为"图像"的缓冲图像(如您的评论所述)

// The required drawing location
int drawLocationX = 300;
int drawLocationY = 300;

// Rotation information

double rotationRequired = Math.toRadians (45);
double locationX = image.getWidth() / 2;
double locationY = image.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);

// Drawing the rotated image at the required drawing locations
g2d.drawImage(op.filter(image, null), drawLocationX, drawLocationY, null);
Run Code Online (Sandbox Code Playgroud)

  • 为什么这么复杂?转换包含旋转和平移,所以只需使用回答中的`tx`做`g2d.drawImage(image,tx,ImageObserver)`. (3认同)
  • 谢谢,但它切断了一些图像. (3认同)

And*_*son 10

AffineTransform实例可以连接(加在一起).因此,您可以将变换结合起来"转换到原点","旋转"和"转换回所需位置".

  • +1 [`RotateApp`](http://stackoverflow.com/a/3420651/230513)就是一个例子. (4认同)

小智 8

我对现有的答案有点挣扎,因为我要旋转的图像并不总是正方形,此外,接受的答案有一条评论询问“有关如何规避截止问题的任何信息”,但未得到答复。因此,对于那些在旋转时遇到图像被裁剪问题的人来说,这里的代码对我有用:

public static BufferedImage rotate(BufferedImage bimg, Double angle) {
    double sin = Math.abs(Math.sin(Math.toRadians(angle))),
           cos = Math.abs(Math.cos(Math.toRadians(angle)));
    int w = bimg.getWidth();
    int h = bimg.getHeight();
    int neww = (int) Math.floor(w*cos + h*sin),
        newh = (int) Math.floor(h*cos + w*sin);
    BufferedImage rotated = new BufferedImage(neww, newh, bimg.getType());
    Graphics2D graphic = rotated.createGraphics();
    graphic.translate((neww-w)/2, (newh-h)/2);
    graphic.rotate(Math.toRadians(angle), w/2, h/2);
    graphic.drawRenderedImage(bimg, null);
    graphic.dispose();
    return rotated;
}
Run Code Online (Sandbox Code Playgroud)