Saturday, June 30, 2012

resize image to required height and width

 How to resize image to required height and width. 


To resize the image firstly need to create a method  'resizeImage()' and pass the required parameters .

Here the 'resizeImage()' method accept 3 parameters (input Stream, required Width , required height )
the code is given below.

public static BufferedImage resizeImage(InputStream in, int requiredWidth, int requiredHeight) throws IOException {
        BufferedImage bfrImage = ImageIO.read(in);


        int imageWidth = bfrImage.getWidth();
        int imageheight = bfrImage.getHeight();
        double scalex = (double) requiredWidth / imageWidth;
        double scaley = (double) requiredHeight / imageheight;
        Image scaledImage = null;

 scaledImage = bfrImage.getScaledInstance(imageWidth, imageheight, Image.SCALE_SMOOTH);

BufferedImage destination = new BufferedImage(requiredWidth, requiredHeight, BufferedImage.SCALE_SMOOTH);
        Graphics2D g2d = destination.createGraphics();
        g2d.scale(scalex, scaley);
        g2d.drawImage(scaledImage, 0, 0, null);
        g2d.dispose();


        return destination;
    }