Java Image Subimage getSubImage(Image image, int x, int y, int width, int height)

Here you can find the source of getSubImage(Image image, int x, int y, int width, int height)

Description

get Sub Image

License

Open Source License

Declaration

public static BufferedImage getSubImage(Image image, int x, int y, int width, int height) 

Method Source Code


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

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;

public class Main {
    public static BufferedImage getSubImage(Image image, int x, int y, int width, int height) {
        if (x >= image.getWidth(null)) {
            throw new IllegalArgumentException(
                    "The given x, " + x + ", must be less than the image width, " + width + ".");
        }//from  www.  j  a  va  2  s  .co m
        if (y >= image.getHeight(null)) {
            throw new IllegalArgumentException(
                    "The given y, " + y + ", must be less than the image height, " + height + ".");
        }
        if (x + width > image.getWidth(null)) {
            throw new IllegalArgumentException(
                    "The given width must be less than or equal to the image width - x.");
        }
        if (y + height > image.getHeight(null)) {
            throw new IllegalArgumentException(
                    "The given height must be less than or equal to the image height - y.");
        }
        BufferedImage subImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        Graphics graphics = subImage.getGraphics();
        graphics.drawImage(image, 0, 0, subImage.getWidth(), subImage.getHeight(), x, y, x + width, y + height,
                null);
        graphics.dispose();
        return subImage;
    }
}