How do you get a subImage that is not a rectangle?
I need to extract a portion of an image that is not rectangular. I know if I convert my image toBufferedImage I can use itsgetSubImage() to return a rectangular image. However what if I wanted a different shape? I've not found any method that returns a more general shaped image.
All I can think of doing is, say for a triangle, something like this:
x
xxx
xxxxx
xxxxxxx
ie, a series ofgetSubImage()s that are one pixel high and a variable length long. Is there any better way to do this? I was hoping for agetPolygon() method.
Joe
[613 byte] By [
32test32a] at [2007-10-2 20:32:24]

Hi, there are several ways to do what you want to, but you have to understand that an object of type "Image" or "BufferedImage" is always rectangular. It has "width" and "height" properties which are dimensions of a rectangle. Suppose you have an object shape instance of Shape:
Shape shape = ...;
You have to create an image (rectangular of coarse) in which the pixels out of shape are transparent:
Rectangle rect = shape.getBounds();
int x = rect.x;
int y = rect.y;
int w = rect.width;
int h = rect.height;
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g = bi.createGraphics();
g.setColor(new Color(255, 255, 255, 0));
g.fillRect(0, 0, w, h);
Now you have to fill the shape with the pixels from the source image (original):
g.setClip(shape);
g.drawImage(original, -x, -y, null);
That's all! Note that the image you created has a type BufferedImage.TYPE_4BYTE_ABGR but the source may have any other type. If you have to preserve the type of the original image you have to do something else.
The complete method:
BufferedImage getSubImage(Shape shape, BufferedImage original){
Rectangle rect = shape.getBounds();
int x = rect.x;
int y = rect.y;
int w = rect.width;
int h = rect.height;
BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g = bi.createGraphics();
g.setColor(new Color(255, 255, 255, 0));
g.fillRect(0, 0, w, h);
g.setClip(shape);
g.drawImage(original, -x, -y, null);
g.dispose();
return bi;
}