2010-06-23 204 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()