Showing posts with label Graphics2D. Show all posts
Showing posts with label Graphics2D. Show all posts
Tuesday, June 11, 2013
Today I will show you how you can flip an image vertically and horizontally. Flipping an image means reflecting an image along a miiror axis. Mathematically when we flip along horizontal axis x'=x and y'=-y whereas when flipped along vertical axis x'=-x and y'=y, where (x',y') is the transformed point and (x,y) is the original point. Here in our sample code we will first read the image from file as BufferedImage. Since there is no flip function available in Java so we will first perform scaling and then translation. We will use AffineTransformOp to transform the image and call filter() method that returns the transformed image.The transformation will be carried out in following way --->
Horizontal Flip : scale(1.0,-1.0) and translate(0,-image.getHeight())
Vertical Flip : scale(-1.0,1.0) and translate(-image.getWidth(),0)
Flip both ways : scale(-1.0,-1.0) and translate(-image.getWidth(),-image.getHeight())
AffineTransform class : It represents a 2D affine transform that performs a linear mapping from 2D coordinates to other 2D coordinates that preserves the "straightness" and "parallelness" of lines. Affine transformations can be constructed using sequences of translations, scales, flips, rotations, and shears.
AffineTransformOp class : This class uses an affine transform to perform a linear mapping from 2D coordinates in the source image or Raster to 2D coordinates in the destination image or Raster. The type of interpolation that is used is specified through a constructor, either by a RenderingHints object or by one of the integer interpolation types defined in this class.
Screenshots of the transformation
Original image
Image after Vertical flip

Image after Horizontal flip
Image after flipping both ways

--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------

import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;


public class FlipImage {
    public BufferedImage flipVertical(BufferedImage src){
    AffineTransform tx=AffineTransform.getScaleInstance(-1.0,1.0);  //scaling
    tx.translate(-src.getWidth(),0);  //translating
    AffineTransformOp tr=new AffineTransformOp(tx,null);  //transforming
   
    return tr.filter(src, null);  //filtering
    }
    
    public BufferedImage flipHorizontal(BufferedImage src){
    AffineTransform tx=AffineTransform.getScaleInstance(1.0,-1.0);  //scaling
    tx.translate(0,-src.getHeight());  //translating
    AffineTransformOp tr=new AffineTransformOp(tx,null);  //transforming
   
    return tr.filter(src, null);  //filtering
    }
    
    public static void main(String[] args)throws Exception {
    FlipImage obj=new FlipImage();
    BufferedImage src=ImageIO.read(new File("src.jpeg"));  //reading image
    BufferedImage dest=obj.flipVertical(src);  //flipping vertically
    ImageIO.write(dest,"jpeg",new File("dest_flipVer.jpg"));
    dest=obj.flipHorizontal(src);  //flipping horizontally
    ImageIO.write(dest,"jpeg",new File("dest_flipHor.jpg"));
    dest=obj.flipVertical(dest); //flupping both ways
    ImageIO.write(dest,"jpeg",new File("dest_flipBoth.jpg"));
    }
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Saturday, February 9, 2013
Today I am going to post how you paint and stroke a shape in java using Graphics2D. But before going into the details of the program I would like to briefly describe about the painting and stroking operation.

•  Painting is the process of filling the interior of the shape with a color, color gradient, or texture. The process of filling the shape interior is done in two steps :
  1. First, tell the Graphics2D how to fill shapes with a call to setPaint(). This method accepts any object that implements the java.awt.Paint interface. The Graphics2D stores the Paint away as part of its state. When it comes time to fill a shape, Graphics2D will use the Paint to determine what colors should be used to fill the shape. The 2D API comes with three kinds of "canned" paints: solid colors, a linear color gradient, and a texture fill. You can add your own Paint implementations if you wish. 
  2. Now you can tell Graphics2Dto fill a shape by passing it to fill()
•  Stroking is the process of drawing the shape's outline. You can draw an outline using different line widths, line styles, and colors. The stroking process is completed in three steps :
  1. First, tell the Graphics2D how you want the outline to be drawn by calling setStroke(). This method accepts any object that implements the java.awt.Stroke interface. The 2D API comes with a class, java.awt.BasicStroke, that implements common stroking options. 
  2. Use setPaint() to tell the Graphics2D how the outline itself should be drawn. Outlines, like the interior of shapes, can be drawn using a color, a gradient, a texture, or anything else that implements the Paint interface. 
  3. Draw the outline of the shape using Graphics2D's draw() method. The Graphics2D uses the Stroke from step 1 to determine what the outline looks like. The Paint from step 2 is used to actually render the outline. 
Screenshot showing painting and stroking

--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.BasicStroke;
import java.awt.GradientPaint;
import javax.swing.JPanel;
import javax.swing.JFrame; 
import java.awt.geom.Ellipse2D;

public class Painting_Stroking extends JPanel{ 

  public static void main(String[] args) {
      JFrame f=new JFrame("PaintingAndStroking v1.0");
      Painting_Stroking obj= new Painting_Stroking();
      f.getContentPane().add(obj);
      f.setSize(320, 150);
      f.setVisible(true);
      f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
  }
  
  public void paintComponent(Graphics g) { 
      Graphics2D g2 = (Graphics2D)g; 
      double x = 15, y = 30, w = 70, h = 70;  //defining shape attributes
      Ellipse2D.Double e = new Ellipse2D.Double(x, y, w, h); 
      GradientPaint gp = new GradientPaint(75, 75, Color.white, 
                       95, 95, Color.gray, true); 
      // Fill with a gradient
      g2.setPaint(gp); 
      g2.fill(e);  //filling first ellipse

      // Stroke with a solid color
      e.setFrame(x + 100, y, w, h); 
      g2.setPaint(Color.black); 
      g2.setStroke(new BasicStroke(8)); 
      g2.draw(e);  //drawing second ellipse with stroke and solid color

      // Stroke with a gradient
      e.setFrame(x + 200, y, w, h); 
      g2.setPaint(gp); 
      g2.draw(e);  //drawing second ellipse with stroke and gradient
   } 
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
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 java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.imageio.ImageIO; 

public class ClipImage extends JPanel{

   @Override
    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
        try{
        //reading image from file
           final BufferedImage image = ImageIO.read(new File("image.jpg"));
           g2.drawImage(image, 0, 0, null);  //drawing image
        }catch(IOException e){
        e.printStackTrace();
        }
    }

    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());
        f.setSize(430,220);
        f.setVisible(true);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
     }
}
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Friday, August 3, 2012
Today I am going to post a program that will create bubbles or a bubbling effect. Here I have used Ellipse2D class. A method calculates random coordinates,sizes and strokes of the ellipses. The size of the ellipses goes on increasing till it reaches its maximum value after which it starts from beginning. Each ellipse reaches its maximum size at different times. Each repainting is done after sleep of every 50ms. Related video is given below
Here is the code for you

import java.awt.*;
import java.awt.geom.Ellipse2D;
import javax.swing.*;

public class Bubbles extends JPanel{
  
    private Ellipse2D.Float[] ellipses;
    private double esize[];
    private float estroke[];
    private final double MAX_SIZE=40;
   
    public Bubbles() {
        ellipses = new Ellipse2D.Float[75];
        esize    = new double[ellipses.length];
        estroke  = new  float[ellipses.length];
        for (int i = 0; i < ellipses.length; i++) {
            ellipses[i] = new Ellipse2D.Float();
            getRandomXY(i, 20 * Math.random(),getWidth()-60,getHeight()-60);
        }
    }
    public void build(){
        while(true){
           for (int i = 0; i < ellipses.length; i++) {
            estroke[i] += 0.025f; //increasing stroke
            esize[i]++; //increasing size
            if (esize[i] > MAX_SIZE)
//new values if reaches maximum
                getRandomXY(i, 20 * Math.random(),getWidth()-60,getHeight()-60);
            else
                ellipses[i].setFrame(ellipses[i].getX(), ellipses[i].getY(),
                                     esize[i], esize[i]);
           }
           repaint();
//repainting
            try {
               Thread.sleep(50);
//sleeping
             }catch (Exception ex) {}
        }
    }
    public void getRandomXY(int i, double size, int w, int h) {
        esize[i] = size;
        estroke[i] = 1.0f;
//setting size.strokes,coordinates
        double x = Math.random() * (getWidth()-(MAX_SIZE/2));
        double y = Math.random() * (getHeight()-(MAX_SIZE/2));
        ellipses[i].setFrame(x, y, size, size);
//setting ellipse
    }
   
    @Override
    public void paintComponent(Graphics g){
        Graphics2D g2d=(Graphics2D)g;
       
//clearing previous trails
        g2d.setColor(Color.black);
        g2d.fillRect(0,0,this.getWidth(),this.getHeight());
        for (int i = 0; i < ellipses.length; i++) {              
               g2d.setStroke(new BasicStroke(estroke[i]));
               int red=(int)(Math.random()*256);
               int green=(int)(Math.random()*256);
               int blue=(int)(Math.random()*256);
               g2d.setColor(new Color(red,green,blue));
               g2d.draw(ellipses[i]);
//drawing ellipses
        }
    }
    public static void main(String[] args) {
        JFrame f=new JFrame("Bubbles");
        Bubbles b=new Bubbles();
        f.getContentPane().add(b);
        f.setSize(350,350);
        f.setVisible(true);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
        b.build();
    }
}
You can also download source file from below links
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared 
Thursday, August 2, 2012
Today I will post how to continously rotate a text i.e string in Java Graphics2D. As you know that there are 4 types of transformation available in Java which are translation,rotation,scaling and shearing. Here I will use translation and rotation for this purpose. The text will be placed exactly at the center of the screen such that mid-point of text and screen coincide. Then the text will be rotated with screen center as the anchor point of rotation. Video of output is given here

Here is the code for you ->

import java.awt.*;
import java.awt.geom.*;
import java.awt.font.*;
import javax.swing.*;

public class RotateText extends JPanel{
    static int angdeg=0;
  
    @Override
    public void paint(Graphics g){
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,                         RenderingHints.VALUE_ANTIALIAS_ON);
         g2d.setColor(Color.white); //
to remove trail of painting
         g2d.fillRect(0,0,getWidth(),getHeight());
         Font font =  new Font("serif",Font.BOLD,50);
         g2d.setFont(font); 
//setting font of surface
         FontRenderContext frc = g2d.getFontRenderContext();
         TextLayout layout = new TextLayout("JAVA", font, frc);
        
//getting width & height of the text
         double sw = layout.getBounds().getWidth();
         double sh = layout.getBounds().getHeight();
        
//getting original transform instance
        AffineTransform saveTransform=g2d.getTransform();
        g2d.setColor(Color.black);
        Rectangle rect = this.getBounds();
        //
drawing the axis
        g2d.drawLine((int)(rect.width)/2,0,(int)(rect.width)/2,rect.height);
        g2d.drawLine(0,(int)(rect.height)/2,rect.width,(int)(rect.height)/2);
        AffineTransform affineTransform = new AffineTransform();    /*
creating instance set the translation to the mid of the component*/
       affineTransform.setToTranslation((rect.width)/2,(rect.height)/2);
      
//rotate with the anchor point as the mid of the text
       affineTransform.rotate(Math.toRadians(angdeg), 0, 0);
       g2d.setTransform(affineTransform);
       g2d.drawString("JAVA",(int)-sw/2,(int)sh/2);
       g2d.setTransform(saveTransform); //
restoring original transform
    }
   
    public static void main(String[] args) throws Exception{
         JFrame frame = new JFrame("Rotated text");
         RotateText rt=new RotateText();
        frame.add(rt);
        frame.setSize(500, 500);
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
      while(true){
             Thread.sleep(10);
//sleeping then increasing angle by 5
             angdeg=(angdeg>=360)?0:angdeg+5; //
             rt.repaint();
//repainting the surface
         }
    }
}


You can also download full source from below links

DOWNLOAD the source from Mediafire 
DOWNLOAD the source from 4shared 

Total Pageviews

Followers


Labels

Popular Posts

free counters