1

我找到了一种在java中旋转图像的方法。

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;
    }

但是这条线上似乎有一个错误

GraphicsConfiguration gc = getDefaultConfiguration();

当我将鼠标悬停在它上面时,它会显示“方法 getDefaultConfiguration() 未针对 Player 类型定义”

这些是我的进口

import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Transparency;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.awt.GraphicsDevice;
import javax.imageio.ImageIO;
4

2 回答 2

2

听起来您找到的示例是使用它自己的方法来获取GraphicsConfiguration

你可以GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration()改用...

于 2013-08-05T02:18:01.373 回答
1

疯狂程序员的回答将修复编译错误但是原始方法不正确(忘记将角度转换为弧度)尝试以下

public static BufferedImage rotateImage(BufferedImage src, double degrees) {
    double radians = Math.toRadians(degrees);

    int srcWidth = src.getWidth();
    int srcHeight = src.getHeight();

    double sin = Math.abs(Math.sin(radians));
    double cos = Math.abs(Math.cos(radians));
    int newWidth = (int) Math.floor(srcWidth * cos + srcHeight * sin);
    int newHeight = (int) Math.floor(srcHeight * cos + srcWidth * sin);

    BufferedImage result = new BufferedImage(newWidth, newHeight,
        src.getType());
    Graphics2D g = result.createGraphics();
    g.translate((newWidth - srcWidth) / 2, (newHeight - srcHeight) / 2);
    g.rotate(radians, srcWidth / 2, srcHeight / 2);
    g.drawRenderedImage(src, null);

    return result;
}
于 2015-05-05T08:56:53.893 回答