在java中旋转图像 [英] Rotate an image in java

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

问题描述

我正在寻找旋转图像。我有一个 JInternalFrame ,其中包含 JLabel 。标签包含图像。旋转图像后,我需要调整内部框架的大小。我目前的代码旋转图像,但图像边缘周围有黑色,并且偏离中心。有关如何解决此问题的任何建议吗?

I am looking to rotate an image. I have a JInternalFrame which contains a JLabel. The label contains the image. After the image has been rotated, I need to resize the internal frame. The code I have currently rotates the image, but there is black around the edges of the image and it is off centered. Any suggestions on how to fix this?

public void rotateIcon(int angle)
{
        int w = theLabel.getIcon().getIconWidth();
        int h = theLabel.getIcon().getIconHeight();
        int type = BufferedImage.TYPE_INT_RGB;  // other options, see api

        BufferedImage DaImage = new BufferedImage(h, w, type);
        Graphics2D g2 = DaImage.createGraphics();

        double x = (h - w)/2.0;
        double y = (w - h)/2.0;
        AffineTransform at = AffineTransform.getTranslateInstance(x, y);

        at.rotate(Math.toRadians(angle), w/2.0, h/2.0);
        g2.drawImage(new ImageIcon(getData()).getImage(), at, theLabel);
        g2.dispose();

        theLabel.setIcon(new ImageIcon(DaImage));
        this.setSize(DaImage.getWidth(),DaImage.getHeight()); //resize the frame
}


推荐答案

你需要使用三角法来确定正确的宽度/高度,使用透明度来防止黑色区域,我认为变换是错误的,这使它偏离中心。

You need to be using trigonometry to determine the correct width/height, using transparency to prevent the black area, and I think the Transform is wrong, which is making it off center.

试试这个:

public static BufferedImage rotate(BufferedImage image, double angle) {
    double sin = Math.abs(Math.sin(angle)), cos = Math.abs(Math.cos(angle));
    int w = image.getWidth(), h = image.getHeight();
    int neww = (int)Math.floor(w*cos+h*sin), newh = (int) Math.floor(h * cos + w * sin);
    GraphicsConfiguration gc = getDefaultConfiguration();
    BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
    Graphics2D g = result.createGraphics();
    g.translate((neww - w) / 2, (newh - h) / 2);
    g.rotate(angle, w / 2, h / 2);
    g.drawRenderedImage(image, null);
    g.dispose();
    return result;
}

private static GraphicsConfiguration getDefaultConfiguration() {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    return gd.getDefaultConfiguration();
}

来自 http://flyingdogz.wordpress.com/2008/02/11/image-rotate-in -java-2-easy-to-use /

这篇关于在java中旋转图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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