Java旋转图像变成全黑?

awe*_*r89 1 java

我正在制作一个基本的Java应用程序并尝试旋转图像.我写了以下快速方法

private Image rotate(double degs){
    ImageIcon img = new ImageIcon("src/inc/img/char_male.png");
    Image temp = new BufferedImage(img.getIconWidth(), img.getIconHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) temp.getGraphics();
    g2.rotate(Math.toRadians(degs));
    g2.drawImage(img.getImage(), 0, 0, Color.WHITE, null);
    System.out.println("Rotating "+degs);
    g2.dispose();
    return temp;
}
Run Code Online (Sandbox Code Playgroud)

问题是当我运行它并重新绘制GUI时,图像变为纯黑色.我是否在创建BufferedImage时出错?我正在使用JLabel更改重绘中的GUI,

label.setIcon(new ImageIcon(rotate(90)));
Run Code Online (Sandbox Code Playgroud)

Hov*_*els 5

您需要同时旋转和平移,以便旋转中心是图像的中心.与Graphics2D旋转方法一样,AffineTransform旋转方法有一个重载.例如,如果你尝试,...

private Image rotate(double degs){
    ImageIcon img = new ImageIcon("src/inc/img/char_male.png"); // why an ImageIcon???
    Image temp = new BufferedImage(img.getIconWidth(), img.getIconHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = (Graphics2D) temp.getGraphics();
    g2.rotate(Math.toRadians(degs), img.getIconWidth()/2, img.getIconHeight()/2); // changed
    g2.drawImage(img.getImage(), 0, 0, Color.WHITE, null);
    System.out.println("Rotating "+degs);
    g2.dispose();
    return temp;
}
Run Code Online (Sandbox Code Playgroud)

对不起,这是更正后的代码:

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class ImageRotate {
   private static final String IMAGE_PATH = "src/yr2011/images/guitar_3406632_n.jpg";

   public static void main(String[] args) {
      try {
         BufferedImage image = ImageIO.read(new File(IMAGE_PATH));
         ImageIcon icon = new ImageIcon(image);
         JOptionPane.showMessageDialog(null, new JLabel(icon));

         icon = new ImageIcon(rotate(image, 90));
         JOptionPane.showMessageDialog(null, new JLabel(icon));
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   private static Image rotate(Image image, double degs) {
      int width = image.getWidth(null);
      int height = image.getHeight(null);
      BufferedImage temp = new BufferedImage(height, width, BufferedImage.TYPE_INT_RGB);
      Graphics2D g2 = temp.createGraphics();
      g2.rotate(Math.toRadians(degs), height / 2, height / 2);
      g2.drawImage(image, 0, 0, Color.WHITE, null);
      g2.dispose();
      return temp;
   }
}
Run Code Online (Sandbox Code Playgroud)