2010-06-23 208 views
1

我想在java中剪切图像的特定形状,例如包含一个白色背景的人的图像,在这里我想剪裁没有背景的人。不想让它成为透明图像,想用一些坐标剪切。我认为使用cropImageFilter我们只能切割矩形区域。任何人都可以告诉我如何做到这一点?java中的图像裁剪

+0

所以,你要准确地切出的人Graphics2D对象,根据人的形状?你意识到这不是一项微不足道的任务吗?计算机很难识别图像中的东西。标准Java库中肯定没有简单的API。 – Jesper 2010-06-23 06:57:40

+0

嗨,Jesper,感谢您的回复,我与我协调,即我有多边形点(坐标)来削减人的形状。有了这个我们可以做任何事吗? – SWDeveloper 2010-06-23 07:13:16

回答

0

首先,您需要从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上。

0

我不确定,但类Graphics2D有一个方法clip()接受一个多边形,我认为你需要做什么。

所以从图像中创建一个BufferedImage,并获得与createGraphics()