Java BufferedImage Crop cropImage(BufferedImage image, int cropWidth, int cropHeight)

Here you can find the source of cropImage(BufferedImage image, int cropWidth, int cropHeight)

Description

Method crop an image to the given dimensions.

License

Open Source License

Parameter

Parameter Description
image Input image
cropWidth Width required for cropped image
cropHeight Height required for cropped image

Return

Cropped image

Declaration

public static BufferedImage cropImage(BufferedImage image, int cropWidth, int cropHeight) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.awt.image.BufferedImage;

public class Main {
    /**//from   w ww.j a  v  a  2 s .  c o  m
     * Method crop an image to the given dimensions. If dimensions are more than the input image size, then the image
     * gets padded with black color
     * 
     * @param image Input image
     * @param cropWidth Width required for cropped image
     * @param cropHeight Height required for cropped image
     * @return Cropped image
     */
    public static BufferedImage cropImage(BufferedImage image, int cropWidth, int cropHeight) {
        BufferedImage retImg = null;
        int width = 0;
        int height = 0;

        width = image.getWidth();
        height = image.getHeight();

        retImg = new BufferedImage(cropWidth, cropHeight, BufferedImage.TYPE_INT_RGB);

        for (int i = 0; i < cropWidth; i++) {
            for (int j = 0; j < cropHeight; j++) {
                if (i < width && j < height) {
                    retImg.setRGB(i, j, image.getRGB(i, j));
                } else {
                    retImg.setRGB(i, j, 0);
                }
            }
        }

        return retImg;
    }
}

Related

  1. crop(final Raster src, final long tx, final long ty, final long minTx, final long maxTy, final int tilesize)
  2. crop4Square(BufferedImage source, File to, int size)
  3. cropAndScaleImage(BufferedImage image, int cropX, int cropY, int cropW, int cropH, int scaleW, int scaleH)
  4. cropBottomTransparent(BufferedImage img)
  5. cropBoundingBox(Rectangle r, int width, int height)
  6. cropImage(BufferedImage image, int fromX, int fromY, int width, int height)
  7. cropImage(BufferedImage image, int lc, int rc, int tc, int bc)
  8. cropImage(BufferedImage image, int width, int height)
  9. cropImage(BufferedImage image, int width, int height)