Tuesday, May 6, 2014
Today in this article I will tell you how to convert an infix expression to postfix expression using stack. This is an important application of stack. Most of the codes that you will find dont take into considerations the exponent and parenthesis. Here in our example we will consider everything and it will be able to convert any infix expression to postfix containing exponent(^) and parenthesis("(",")"). In our example we have also shown the current symbol processed, stack status and current postfix expression. We have solved it in the following way

  • First push a sentinel element # to denote end of stack
  • Scan each symbol of input infix expression
  • If symbol is operator then check precedence with operator on stack top and take necessary action
  • If left parenthesis then push it, and if right parenthesis then pop continously from stack till a left parenthesis is found
  • If all symbols are scanned then pop all elements from stack and ad to postfix till # found.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.util.Scanner;
import java.util.Stack;

public class InfixToPostfix {

 /**
  * Checks if the input is operator or not
  * @param c input to be checked
  * @return true if operator
  */
 private boolean isOperator(char c){
  if(c == '+' || c == '-' || c == '*' || c =='/' || c == '^')
   return true;
  return false;
 }
 
 /**
  * Checks if c2 has same or higher precedence than c1
  * @param c1 first operator
  * @param c2 second operator
  * @return true if c2 has same or higher precedence
  */
 private boolean checkPrecedence(char c1, char c2){
  if((c2 == '+' || c2 == '-') && (c1 == '+' || c1 == '-'))
   return true;
  else if((c2 == '*' || c2 == '/') && (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/'))
   return true;
  else if((c2 == '^') && (c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/'))
   return true;
  else
   return false;
 }
 
 /**
  * Converts infix expression to postfix
  * @param infix infix expression to be converted
  * @return postfix expression
  */
 public String convert(String infix){
  System.out.printf("%-8s%-10s%-15s\n", "Input","Stack","Postfix");
  String postfix = "";  //equivalent postfix is empty initially
  Stack<Character> s = new Stack<>();  //stack to hold symbols
  s.push('#');  //symbol to denote end of stack

  System.out.printf("%-8s%-10s%-15s\n", "",format(s.toString()),postfix);  

  for(int i = 0; i < infix.length(); i++){
   char inputSymbol = infix.charAt(i);  //symbol to be processed
   if(isOperator(inputSymbol)){  //if a operator
    //repeatedly pops if stack top has same or higher precedence
    while(checkPrecedence(inputSymbol, s.peek()))
     postfix += s.pop();
    s.push(inputSymbol);
   }
   else if(inputSymbol == '(')
    s.push(inputSymbol);  //push if left parenthesis
   else if(inputSymbol == ')'){
    //repeatedly pops if right parenthesis until left parenthesis is found
    while(s.peek() != '(') 
     postfix += s.pop();
    s.pop();
   }
   else
    postfix += inputSymbol;
   System.out.printf("%-8s%-10s%-15s\n", ""+inputSymbol,format(s.toString()),postfix);  
  }

  //pops all elements of stack left
  while(s.peek() != '#'){
   postfix += s.pop();
   System.out.printf("%-8s%-10s%-15s\n", "",format(s.toString()),postfix);  

  }
  
  return postfix;
 }
 
 /**
  * Formats the input  stack string
  * @param s It is a stack converted to string
  * @return formatted input
  */
 private String format(String s){
  s = s.replaceAll(",","");  //removes all , in stack string
  s = s.replaceAll(" ","");  //removes all spaces in stack string
  s = s.substring(1, s.length()-1);  //removes [] from stack string
  
  return s;
 }
 
 public static void main(String[] args) {
  InfixToPostfix obj = new InfixToPostfix();
  Scanner sc = new Scanner(System.in);
  System.out.print("Infix : \t");
  String infix = sc.next();
  System.out.print("Postfix : \t"+obj.convert(infix));
 }
}
-------------------------------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------------------------------
Infix :         A+(B*C-(D/E^F)*G)*H
Input   Stack     Postfix
        #
A       #         A
+       #+        A
(       #+(       A
B       #+(       AB
*       #+(*      AB
C       #+(*      ABC
-       #+(-      ABC*
(       #+(-(     ABC*
D       #+(-(     ABC*D
/       #+(-(/    ABC*D
E       #+(-(/    ABC*DE
^       #+(-(/^   ABC*DE
F       #+(-(/^   ABC*DEF
)       #+(-      ABC*DEF^/
*       #+(-*     ABC*DEF^/
G       #+(-*     ABC*DEF^/G
)       #+        ABC*DEF^/G*-
*       #+*       ABC*DEF^/G*-
H       #+*       ABC*DEF^/G*-H
        #+        ABC*DEF^/G*-H*
        #         ABC*DEF^/G*-H*+
Postfix :       ABC*DEF^/G*-H*+

-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Sunday, May 4, 2014
To day in this article I will tell you how to resize or scale an image in Java. Many times while developing an application you maya need this. Most often you may require to create a thumbnail of an image in most web applications. This tutorial will guide you describing each steps in detail.

  • First read an image from file or URL using ImageIO
  • Now create a BufferedImage with specified width, height and image type
  • Obtain a Graphics2D object from the destination object create in earlier step
  • Draw the original image using the Graphics object
  • Dispose the Graphics object
  • Return or save the final image
Here in our example we will have a class with 3 methods.
Original image (930 x 520)  to be resized or scaled

  • resizeImage() : This method takes in a source image, the width and height of destination image. This is most simple method and follows the steps mentioned above
    Image resized (100 x 100) without hints
  • BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = dest.createGraphics();
    g2d.drawImage(src, 0, 0, width, height, null);
    g2d.dispose();
    return dest;
  • resizeImageWithHints() : This is a slightly modified version of the above method. Here rendering hints and alpha composite are added to the destination image as shown below
    Image resized (100 x 100) with hints
  • g2d.setComposite(AlphaComposite.Src);
    g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  • scaleImage() : This method takes input a source image and the scale factor varying from 0 to 1. The most important feature of this method is that it reserves i.e. maintains the aspect ratio of original image. Here an AffineTransform instance is created and the image is drwan with that instance
    Image scaled = 0.3 (279 x 156)
  • AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
    g2d.drawRenderedImage(src, at);
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

public class ImageResizer {
 
 /**
  * Resizes an image without rendering hints depending on input width, height
  * @param src source image to be resized
  * @param width width of destination image
  * @param height height of destination image
  * @return resized image
  */
 public BufferedImage resizeImage(BufferedImage src,int width,int height){
  BufferedImage dest = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
  Graphics2D g2d = dest.createGraphics();
  g2d.drawImage(src, 0, 0, width, height, null);
  g2d.dispose();
  
  return dest;
 }
 
 /**
  * Resizes an image with rendering hints depending on input width, height
  * @param src source image to be resized
  * @param width width of destination image
  * @param height height of destination image
  * @return resized image
  */
 public BufferedImage resizeImageWithHints(BufferedImage src,int width,int height){
  BufferedImage dest = new BufferedImage(width, height, src.getType());
  Graphics2D g2d = dest.createGraphics();
  
  g2d.setComposite(AlphaComposite.Src);
  g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
  g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
  g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  
  g2d.drawImage(src, 0, 0, width, height, null);
  g2d.dispose();
  
  return dest;
 }
 
 /**
  * Scales an image depending on sclae factor and maintains
  * the aspect ratio of original image
  * @param src source image to be scaled
  * @param scale scale factor xscale = yscale
  * @return scaled image
  */
 public BufferedImage scaleImage(BufferedImage src, double scale){
  int w = (int)(src.getWidth()*scale);
  int h = (int)(src.getHeight()*scale);
  BufferedImage dest = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  Graphics2D g2d = dest.createGraphics();
  AffineTransform at = AffineTransform.getScaleInstance(scale, scale);
  g2d.drawRenderedImage(src, at);
  
  return dest;
 }
 
 public static void main(String... args) throws Exception {
  ImageResizer resizer = new ImageResizer();
  BufferedImage src = ImageIO.read(new File("original.jpg"));

  BufferedImage dest = resizer.resizeImage(src, 100, 100);
  ImageIO.write(dest, "jpeg", new File("dest-resize.jpg"));
  
  dest = resizer.resizeImageWithHints(src, 100, 100);
  ImageIO.write(dest, "jpeg", new File("dest-resize-hints.jpg"));
  
  dest = resizer.scaleImage(src, 0.3);
  ImageIO.write(dest, "jpeg", new File("dest-scale.jpg"));
 }
}
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared

Total Pageviews

Followers


Labels

Popular Posts

free counters