我忙於擺弄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