【发布时间】:2016-02-19 14:02:12
【问题描述】:
我正忙于摆弄 Java 的 Graphics2D 和绘图,虽然它可以工作,但我不确定如何从这个图形创建一个 BufferedImage,我似乎需要这样做才能将它保存在某个地方。
我有一些非常基本的东西,因为我试图了解它是如何工作的
import javax.swing.*;
import javax.imageio.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
public class myFrame {
public static void main(String[] args) {
JFrame lv_frame = new JFrame();
lv_frame.setTitle("Drawing");
lv_frame.setSize(300, 300);
lv_frame.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
lv_frame.add(new drawingPanel(5, 5));
lv_frame.setVisible(true);
}
}
class drawingPanel extends JPanel {
public drawingPanel(int x, int y) {
}
public void draw(Graphics graphic) {
Graphics2D graphic2D = (Graphics2D) graphic;
graphic2D.fillArc(0, 0, 50, 50, 0, 45);
graphic2D.fillArc(0, 0, 50, 50, 135, 45);
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_BGR);
try {
graphic2D = image.createGraphics();
File output = new File("output.png");
ImageIO.write(image, "png", output);
} catch(IOException log) {
System.out.println(log);
}
}
public void paintComponent(Graphics graphic) {
super.paintComponent(graphic);
draw(graphic);
}
}
这没问题,除了我得到一个空白 png 作为我的 output.png 并且我不知道为什么虽然我相当确定我的代码是非常错误的
工作版本
import javax.swing.*;
import javax.imageio.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
public class myFrame {
public static void main(String[] args) {
JFrame lv_frame = new JFrame();
lv_frame.setTitle("Drawing");
lv_frame.setSize(300, 300);
lv_frame.setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
lv_frame.add(new drawingPanel());
lv_frame.setVisible(true);
}
}
class drawingPanel extends JPanel {
public void paintComponent(Graphics graphic) {
super.paintComponent(graphic);
draw(graphic);
saveImage();
}
public void draw(Graphics graphic) {
Graphics2D graphic2D = (Graphics2D) graphic;
Color color = Color.decode("#DDDDDD");
graphic2D.setPaint(color);
graphic2D.fillArc(0, 0, 50, 50, 0, 45);
graphic2D.fillArc(0, 0, 50, 50, 135, 45);
}
public void saveImage() {
BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_BGR);
Graphics2D graphic2D = image.createGraphics();
try {
File output = new File("output.png");
draw(graphic2D);
ImageIO.write(image, "png", output);
} catch(IOException log) {
System.out.println(log);
}
}
}
【问题讨论】:
-
正如@Hovercraft Full Of Eels 在他的评论中所说,如果您从您的
paintComponent方法调用saveImage,则每次重新绘制JPanel时,该文件都会被覆盖。这真的是你想要在那里做的吗? -
是的,每次绘制图像时都必须保存它,所以我不希望它们被单独调用
标签: java swing output bufferedimage graphics2d