2013-08-05 65 views
1

我找到了一种在Java中旋转图像的方法。Image Rotation 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()是未定义的类型的球员”

这是我进口

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; 

回答

2

这听起来像你发现的例子是使用它自己的方法获取GraphicsConfiguration

你可以使用GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration(),而不是...

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