2013-08-05 108 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; 
}