import java.awt.*; import java.awt.image.*; import java.awt.event.*; import java.awt.geom.*; import javax.imageio.*; import javax.swing.*; import java.io.*; /** BufferedImageDemo * * Shows how to create & use a local BufferedImage * Shows how to draw on it with low-level and high-level tools * Shows how to save image using the local BufferedImage * * M.Lampton (c) 2015 UCB SSL */ public class BufferedImageDemo { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } private static void createAndShowGUI() { JFrame jf = new PlotFrame(); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } } class PlotFrame extends JFrame { public PlotFrame() { setTitle("BufferedImageDemo"); setSize(400, 400); final PlotPanel panel = new PlotPanel(); Container contentPane = getContentPane(); contentPane.add(panel); JMenu fileMenu = new JMenu("File"); fileMenu.add(new AbstractAction("Write PNG") { public void actionPerformed(ActionEvent event) { PlotPanel.bPNG = true; repaint(); } }); fileMenu.add(new AbstractAction("Exit") { public void actionPerformed(ActionEvent event) { System.exit(0); } }); JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); menuBar.add(fileMenu); } } class PlotPanel extends JPanel { static BufferedImage bi; // local static Graphics2D g2bi; // local static Graphics2D g2screen; // from OS public static boolean bPNG = false; public void paintComponent(Graphics g) { super.paintComponent(g); g2screen = (Graphics2D) g; //---create a local bitmap--------- int w = this.getWidth(); // local width int h = this.getHeight(); // local height System.out.println("W="+w+" H="+h); bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB); g2bi = bi.createGraphics(); g2bi.setPaint(Color.WHITE); g2bi.fillRect(0, 0, w, h); // Paints bitmap white. //----get the artwork--------- MyArt.doArt(bi); //----blit the artwork to the screen------ g2screen.drawImage(bi, 0, 0, null); //---if requested, save the image-------- if (bPNG) { try { ImageIO.write(bi, "png", new File("out.png")); System.out.println("Image saved."); } catch (Exception e) { System.out.println("Image could not be saved."); } } bPNG = false; } } /** Artwork generator class demonstrates low-level and high-level tools. * The Graphics2D context can be obtained from a BufferedImage, * but a BufferedImage cannot be obtained from a Graphics2D context. * To use both tools we need both the BufferedImage and the Graphics2D. * So, communicate the BufferedImage to make both tools available. */ class MyArt { static void doArt(BufferedImage bi) { int width = bi.getWidth(); int height = bi.getHeight(); //-----some low level bit work-------- //-----draw ONLY legal pixels--------- int icolor = new Color(255, 223, 105).getRGB(); int radius = 166; int r2 = radius*radius; int ihc = width/2; int ivc = height/2; for (int ih=0; ih