The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.imageio  [6 examples]

e695. Saving a Generated Graphic to a PNG or JPEG File

This example demonstrates how to create a generated image and save it as a PNG or JPEG file.
    // Create an image to save
    RenderedImage rendImage = myCreateImage();
    
    // Write generated image to a file
    try {
        // Save as PNG
        File file = new File("newimage.png");
        ImageIO.write(rendImage, "png", file);
    
        // Save as JPEG
        file = new File("newimage.jpg");
        ImageIO.write(rendImage, "jpg", file);
    } catch (IOException e) {
    }
    
    // Returns a generated image.
    public RenderedImage myCreateImage() {
        int width = 100;
        int height = 100;
    
        // Create a buffered image in which to draw
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    
        // Create a graphics contents on the buffered image
        Graphics2D g2d = bufferedImage.createGraphics();
    
        // Draw graphics
        g2d.setColor(Color.white);
        g2d.fillRect(0, 0, width, height);
        g2d.setColor(Color.black);
        g2d.fillOval(0, 0, width, height);
    
        // Graphics context no longer needed so dispose it
        g2d.dispose();
    
        return bufferedImage;
    }

 Related Examples
e694. Reading an Image from a File, InputStream, or URL
e696. Listing the Image Formats That Can Be Read and Written
e697. Determining If an Image Format Can Be Read or Written
e698. Determining the Format of an Image in a File
e699. Compressing a JPEG File


© 2002 Addison-Wesley.