2016-04-04 87 views
1

我試圖旋轉緩衝的Image並使用getImage()方法返回緩衝的Image(旋轉圖像)。圖像旋轉正在發生,但在保存圖像的同時不保存圖像旋轉。如何將旋轉的緩衝圖像保存在另一個緩衝圖像中?

初始化:

private BufferedImage transparentImage; 

的paintComponent:

AffineTransform at = new AffineTransform(); 
at.rotate(Math.toRadians(RotationOfImage.value)); 
Graphics2D g2d = (Graphics2D) g; 

g2d.drawImage(transparentImage, at, null); 
repaint(); 

返回旋轉緩衝圖像的方法。

public BufferedImage getImage(){ 
    return transparentImage; 
} 
+1

你爲什麼在'paintComponent'中旋轉它?您應該繪製旋轉的圖像。按照您的方式進行操作不會對圖像產生任何影響,因爲您正在旋轉組件的「圖形」上下文 – MadProgrammer

回答

2

基本上,你的旋轉組件的Graphics背景和繪畫的形象吧,這將有原始圖像沒有影響。

相反,你應該旋轉圖像和畫它,例如...

public BufferedImage rotateImage() { 
    double rads = Math.toRadians(RotationOfImage.value); 
    double sin = Math.abs(Math.sin(rads)); 
    double cos = Math.abs(Math.cos(rads)); 

    int w = transparentImage.getWidth(); 
    int h = transparentImage.getHeight(); 
    int newWidth = (int) Math.floor(w * cos + h * sin); 
    int newHeight = (int) Math.floor(h * cos + w * sin); 

    BufferedImage rotated = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_ARGB); 
    Graphics2D g2d = rotated.createGraphics(); 
    AffineTransform at = new AffineTransform(); 
    at.translate((newWidth - w)/2, (newHeight - h)/2); 

    at.rotate(Math.toRadians(RotationOfImage.value), w/2, h/2); 
    g2d.setTransform(at); 
    g2d.drawImage(transparentImage, 0, 0, this); 
    g2d.setColor(Color.RED); 
    g2d.drawRect(0, 0, newWidth - 1, newHeight - 1); 
    g2d.dispose(); 
} 

然後,你可以畫它做這樣的事情......

@Override 
protected void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    Graphics2D g2d = (Graphics2D) g.create(); 
    BufferedImage rotated = rotateImage(); 
    int x = (getWidth() - rotated.getWidth())/2; 
    int y = (getHeight() - rotated.getHeight())/2; 
    g2d.drawImage(rotated, x, y, this); 
    g2d.dispose(); 
} 

現在,你可以優化這個,所以你只生成一個旋轉版本的圖像時,角度已經改變,但我會離開這個由你決定

ps-我沒有測試過這個,但它是基於這個question

+0

*「ps-我沒有測試過這個..」* Pfft ..多少次你做到了嗎?我確信我可以回想起在這個網站至少看到** 3次(而我的記憶很差)。 –

+0

@AndrewThompson因爲我從庫代碼中複製了算法,所以希望它的工作原理如下:P – MadProgrammer

+0

Meh .. BNI ... ;-) –