How to save a drawing made with java graphics as a independent object

别等时光非礼了梦想. 提交于 2021-02-11 12:20:25

问题


my problem is that I need to save the things that I draw with java graphics as independent objects, to later recolor them, erase them indepently...

Here is my eclipse project for you to import. (The main class is the Paint class)

This is the method I use to draw:

  protected void paintComponent(Graphics g) {
if (imagen == null) {
  imagen = createImage(getSize().width, getSize().height);
  graficos = (Graphics2D) imagen.getGraphics();
  graficos.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  clear();
}
g.drawImage(imagen, 0, 0, null); }

I call this function through MouseMotionListener and I get to draw. But of course this simply makes it appear and I would need to save the drawings between click and click


回答1:


The basic logic for creating an image of any component is:

Dimension d = component.getSize();
BufferedImage image = new BufferedImage(d.width, d.height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = image.createGraphics();
component.print( g2d );
g2d.dispose();
ImageIO.write(image, ".jpg", new File(...));

You can check out Screen Image for a reusable class that does this for you and provides a few more features.



来源:https://stackoverflow.com/questions/64390844/how-to-save-a-drawing-made-with-java-graphics-as-a-independent-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!