我忙于摆弄Java的Graphics2D和绘图,尽管它工作正常,但我不确定如何从该图形创建一个BufferedImage,看起来我需要这样做才能将它保存到某个位置。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,我不知道为什么,虽然我“M相当肯定我的代码是可怕的错误
工作版本
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全部鳗鱼在说他的评论,如果你从'paintComponent'方法中调用'saveImage',那么每次'JPanel'被重新绘制时,文件都会被覆盖。这真的是你想要做的吗? – Berger
是的,每次绘制图像时都必须保存,所以我不希望它们被单独调用 – Trent