我想在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 上。
关于java - java中的图像裁剪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3099497/