Create an image with rounded corners

Here is how you can reshape/clip an image into the shape you like. Sometimes, we want to shape an image into a rounded rectangle. We generally use image editing software like photoshop to do this. Did you know that we can do it ourselves in Java? That too in a simpler way than you think of? Let us see how to do this.


RoundAnImage.java

import javax.imageio.*;
import java.awt.image.*;
import java.io.*;
import java.awt.*;
import java.awt.geom.*;
class RoundAnImage {
    public static void main(String args[]) throws Exception {
        // Get the BufferedImage object for the image file
        BufferedImage originalImg = ImageIO.read(new File(args[0]));

        // Get the width,height of the image
        int width = originalImg.getWidth();
        int height = originalImg.getHeight();

        // Create a new BufferedImage object with the width,height
        // equal to that of the image file
        BufferedImage bim = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

        // Create a Graphics2D object by using
        // createGraphics() method. This object is 
        // used to perform the operation!
        Graphics2D g2 = bim.createGraphics();

        // You can also use rendering hints
        // to smooth 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);

        // This method does it all!. You can clip the
        // image into the shape you wish, play it as you like!
        g2.setClip(new RoundRectangle2D.Double(0, 0, width, height, width / 4, height / 4));

        // Now, draw the image. The image is now
        // in the 'clipped' shape, the shape in the setClip()
        g2.drawImage(originalImg, 0, 0, null);

        // Dispose it, we no longer need it.
        g2.dispose();

        // Write to a new image file
        ImageIO.write(bim, "PNG", new File(args[0] + "-rounded.png"));
    }
}

Output of the program

Corners are too much rounded only to clearly show the effect

Also, don’t forget to drop your eyes on other posts draw and save an image in java and pasting an image from clipboard

If you are a swing lover, you will probably like setting background image in jframe and setting background image for jmenubar

No comments: