Monday, January 21, 2013
Today I am going to post a program that will use a text string as a clipping path and draw an image with it. As you know, Graphics2D can do a number of operations like transformations,clipping and alpha compositing. Here in our case, we will use images. First of all we will rotate the user space. This is just to give our output a more better look. The clipping shape is created in the method getClippingShape(Graphics) method. Here a text is chosen and a Font instance is created. This font is used to create GlyphVector for the clipping shape string. Then the shape is retrieved by calling getOutline() method of GlyphVector. The clip method of Graphics2D is called, followed by reading of the image from file using ImageIO's read method. Finally the image is drawn on panel and displayed.
Screenshots of original and final images
Origibal Image
Final Clip Image

Java Source Code

import java.awt.*; 
import java.awt.font.*; 
import java.awt.image.BufferedImage; 
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.imageio.ImageIO; 

public class ClipImage extends JPanel{

    public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;  //casting
        Dimension d = getSize();
        g2.rotate(-Math.PI / 12, d.width / 2, d.height / 2);  //rotating
        g2.clip(getClippingShape(g2));  //clipping
        //reading image from file
           final BufferedImage image = File("image.jpg"));
           g2.drawImage(image, 0, 0, null);  //drawing image
        }catch(IOException e){

    private Shape getClippingShape(Graphics2D g2) {
          String s = "Java 2D";  //defining clipping text
          Font font = new Font("Serif", Font.PLAIN, 122);  //text font
          FontRenderContext frc = g2.getFontRenderContext(); 
          GlyphVector gv = font.createGlyphVector(frc, s);  //text glyph
          Shape clippingShape = gv.getOutline(10, 120);  //getting clip shape
          return clippingShape; //returning shape
     public static void main(String[] args){ 
        JFrame f=new JFrame("Clipping_Image");
        f.getContentPane().add(new ClipImage());
Download Links
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared


Post a Comment

Total Pageviews

Subscribe via Email


Popular Posts

About Me

My photo

I am a student of BTech Computer Science Engineering from RCCIIT,Kolkata. I am a crazy lover of Java and wants to settle as a Java developer. I have a seven years Java experience with an application developer experience for 2 years. Recently from March 2012 I am a registered S40 app developer for Nokia and has corrected an app of them. I am currently writing blogs to encourage and grow interest in all those who don't know or learning Java.