gpt4 book ai didi

Java旋转图像变成全黑?

转载 作者:行者123 更新时间:2023-11-29 06:24:04 25 4
gpt4 key购买 nike

我正在制作一个基本的 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;
}

问题是当我运行它并重新绘制 GUI 时,图像变成了纯黑色。我在创建 BufferedImage 时做错了什么吗?我正在使用 JLabel 更改重绘中的 GUI,

label.setIcon(new ImageIcon(rotate(90)));

最佳答案

需要同时旋转和平移,使旋转的中心为图像的中心。 AffineTransform 旋转方法与 Graphics2D 旋转方法一样为此具有重载。例如,如果您尝试...

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

抱歉,这是更正后的代码:

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

关于Java旋转图像变成全黑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5925616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com