Saving a Java 2d graphics image as .png file

后端 未结 4 1564
刺人心
刺人心 2020-11-30 06:54

I am drawing a graphical representation of information my simulation is generating. I have the graph displaying but the problem i am running into is to be able to save it a

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-30 07:20

    See this example: Draw an Image and save to png.


    import java.awt.BasicStroke;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.FontMetrics;
    import java.awt.GradientPaint;
    import java.awt.Graphics2D;
    import java.awt.geom.Ellipse2D;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    
    import javax.imageio.ImageIO;
    
    public class WriteImageType {
      static public void main(String args[]) throws Exception {
        try {
          int width = 200, height = 200;
    
          // TYPE_INT_ARGB specifies the image format: 8-bit RGBA packed
          // into integer pixels
          BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    
          Graphics2D ig2 = bi.createGraphics();
    
    
          Font font = new Font("TimesRoman", Font.BOLD, 20);
          ig2.setFont(font);
          String message = "www.java2s.com!";
          FontMetrics fontMetrics = ig2.getFontMetrics();
          int stringWidth = fontMetrics.stringWidth(message);
          int stringHeight = fontMetrics.getAscent();
          ig2.setPaint(Color.black);
          ig2.drawString(message, (width - stringWidth) / 2, height / 2 + stringHeight / 4);
    
          ImageIO.write(bi, "PNG", new File("c:\\yourImageName.PNG"));
          ImageIO.write(bi, "JPEG", new File("c:\\yourImageName.JPG"));
          ImageIO.write(bi, "gif", new File("c:\\yourImageName.GIF"));
          ImageIO.write(bi, "BMP", new File("c:\\yourImageName.BMP"));
    
        } catch (IOException ie) {
          ie.printStackTrace();
        }
    
      }
    }
    

提交回复
热议问题