我想在Java中剪切图像的特定形状,例如,包含一个带有白色背景的男人的图像,在这里,我想裁剪没有背景的男人。不想将其制作为透明图像,想要使用一些坐标进行切割。我认为使用cropImageFilter,我们只能剪切矩形区域。谁能给我打电话怎么做?
最佳答案
首先,您需要从java.awt.Image创建一个java.awt.image.BufferedImage。这是从DZone Snippets开始的一些代码。
/**
* @author Anthony Eden
*/
public class BufferedImageBuilder {
private static final int DEFAULT_IMAGE_TYPE = BufferedImage.TYPE_INT_RGB;
public BufferedImage bufferImage(Image image) {
return bufferImage(image, DEFAULT_IMAGE_TYPE);
}
public BufferedImage bufferImage(Image image, int type) {
BufferedImage bufferedImage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
Graphics2D g = bufferedImage.createGraphics();
g.drawImage(image, null, null);
waitForImage(bufferedImage);
return bufferedImage;
}
private void waitForImage(BufferedImage bufferedImage) {
final ImageLoadStatus imageLoadStatus = new ImageLoadStatus();
bufferedImage.getHeight(new ImageObserver() {
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
if (infoflags == ALLBITS) {
imageLoadStatus.heightDone = true;
return true;
}
return false;
}
});
bufferedImage.getWidth(new ImageObserver() {
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
if (infoflags == ALLBITS) {
imageLoadStatus.widthDone = true;
return true;
}
return false;
}
});
while (!imageLoadStatus.widthDone && !imageLoadStatus.heightDone) {
try {
Thread.sleep(300);
} catch (InterruptedException e) {
}
}
}
class ImageLoadStatus {
public boolean widthDone = false;
public boolean heightDone = false;
}
}
有了BufferedImage之后,您就可以使用该多边形坐标来将非人类像素变成透明像素。只需使用BufferedImage中提供的方法即可。
您不能从字面上从BufferedImage剪切多边形。 BufferedImage必须是矩形。最好的办法是使不需要的图像部分透明。或者,您可以将所需的像素放在另一个矩形BufferedImage上。