Draw and Save an image in Java

Image of a palm tree from Dragoart.com
Let us now draw and save an image in Java. In this program, i will be painting a simple gradient paint on the image that contains a rounded rectangle with transparent and smooth edges. This is really, really simple. Just go through the program, you'll understand how easy it is.






import javax.imageio.*;
import java.awt.image.*;
import java.awt.*;
import java.io.*;
class DrawImage
{
private GradientPaint gp;
private int width,height;

    public DrawImage(int width,int height,GradientPaint gp)
    {
        this.width=width;
        this.height=height;
        this.gp=gp;
        drawImage();
    }
   
    private void drawImage()
    {
        // Create a BufferedImage object specifying width,height of the image
        // and also the type (here alpha-red-green-blue)
        BufferedImage bim=new BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
      
        // Create Graphics object
        // Graphics2D is a sub class of the Graphics class,
        // so this statement is correct
        Graphics2D g2=bim.createGraphics();
      
        // Set the paint
        g2.setPaint(gp);
      
        // You can also use rendering hints
        // to smoothen the edges or the rounded rectangle
        RenderingHints qualityHints = new RenderingHints(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        qualityHints.put(RenderingHints.KEY_RENDERING,RenderingHints.VALUE_RENDER_QUALITY);
        g2.setRenderingHints(qualityHints);
      
        // Fill the round rectangle from (0,0) and the paint
        // should spread over the entire width and height
        // and the corner radius width,height is 1/4th of
        // the corresponding dimension
        g2.fillRoundRect(0,0,width,height,width/4,height/4);
      
        // Dispose the Graphics2D object
        g2.dispose();
      
        // Throws IOException
        try
        {
            // Write the BufferedImage object to a file
            // The type of the image here is made PNG for
            // transparent edges as the image contains a
            // rounded rectangle
            ImageIO.write(bim,"PNG",new File("output_image.png"));
        }catch(Exception e){}
    }
   
    public static void main(String args[])
    {
        // Invoke the constructor sending the width,height
        // and the GradientPaint object
        // The GradientPaint object defines a gradient
        // consisting of two colors with their starting and ending points
        new DrawImage(400,400,new GradientPaint(0,0,Color.BLUE,0,400,Color.CYAN));
    }
}

Share the post, if you enjoy it, also don't forget to check out the post convert images in Java from one format to the other and also pasting an image from clipboard.

Don't hesitate to drop a comment if there is any problem in understanding drawing and saving the image or if you have any bug.


Posted by at on

Tags: Image IO, Working with Images,