2

目前我正在使用这段代码(我在这里找到)在 Java 中旋转图像。该代码运行良好,但我对旋转图像的质量不满意。

我该如何改进它?它需要一个单独的库吗?

public static BufferedImage rotate(BufferedImage image, float angle) {
    float radianAngle = (float) Math.toRadians(angle) ; 

    float sin = (float) Math.abs(Math.sin(radianAngle));
    float cos = (float) Math.abs(Math.cos(radianAngle));

    int w = image.getWidth() ;
    int h = image.getHeight();

    int neww = (int) Math.round(w * cos + h * sin);
    int newh = (int) Math.round(h * cos + w * sin);

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    GraphicsConfiguration gc = gd.getDefaultConfiguration();

    BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
    Graphics2D g = result.createGraphics();

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    g.translate((neww-w)/2, (newh-h)/2);
    g.rotate(radianAngle, w/2, h/2);

    g.drawRenderedImage(image, null);
    g.dispose();

    return result;
}
4

1 回答 1

6

你应该设置RenderingHints.KEY_INTERPOLATIONRenderingHints.KEY_RENDERING

这是完整的工作代码:

public static BufferedImage rotate(BufferedImage image, float angle) {
    float radianAngle = (float) Math.toRadians(angle) ; 

    float sin = (float) Math.abs(Math.sin(radianAngle));
    float cos = (float) Math.abs(Math.cos(radianAngle));

    int w = image.getWidth() ;
    int h = image.getHeight();

    int neww = (int) Math.round(w * cos + h * sin);
    int newh = (int) Math.round(h * cos + w * sin);

    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice gd = ge.getDefaultScreenDevice();
    GraphicsConfiguration gc = gd.getDefaultConfiguration();

    BufferedImage result = gc.createCompatibleImage(neww, newh, Transparency.TRANSLUCENT);
    Graphics2D g = result.createGraphics();

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON) ;

    // this will further improve the quality
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
    g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);

    AffineTransform at = AffineTransform.getTranslateInstance((neww-w)/2, (newh-h)/2);
    at.rotate(radianAngle, w/2, h/2);

    g.drawRenderedImage(image, at);
    g.dispose();

    return result;
}
于 2013-04-20T13:14:21.160 回答