2014-01-10 31 views
0

我在模擬動畫,我用於實體的圖像是黑白的小PNG文件(如果這有什麼區別)。我想知道是否有任何方法可以改變圖像的顏色(例如將黑色更改爲紅色,或將紅色過濾器覆蓋黑色),一旦將其導入爲BufferedImage?或者,我最好是在Java外部創建獨立的圖標顏色版本,並將它們作爲單獨的圖像導入?是否可以修改Java Swing中圖像的顏色?

+0

http://stackoverflow.com/questions/23763/colorizing-images-in-java – PeterMmm

+0

如果你正在處理的實際圖像,然後我會假設使用單獨的彩色版本的圖像會更容易**,這是說我並不是說你的方式是不可能的,但它可能很難實現。 –

+0

請參閱[使用映像](http://docs.oracle.com/javase/tutorial/2d/images/index.html)。你可能會發現有用的東西。 –

回答

2

可以使用 java.awt.image.RGBImageFilter中 類

我個人haven`t打了,我走了另一條道路,這是越來越圖標進入像素(整型)數組,操縱這個我自己。

就這樣,可以創建ImageSourceInt的實例(如我稱之爲)使一個ImageIcon,與它周圍擺弄

(canvasData是像素陣列中ARGB-INT格式 - 1字節每每個信道= 4字節= 1 int)

並檢索一個BufferedImage(一個視圖,而不是一個副本),以便與Swing一起使用。

對於後者,調用getReferenceImage()方法。順便說一句,如果你不知道scanSize(成像中的常見術語),只是將其視爲圖像的寬度。

(對不起,糟糕的代碼格式,我真的是新來的)

public class ImageSourceInt implements ImageSource { 

int[] canvasData; 

int width; 

int height; 

int scanSize; 

int lineCount; 


/** 
* @param source make sure it is loaded or this ImageSource will be empty.<br> 
* sizeIncrementWidth and sizeIncrementHeight are set to 1 
*/ 
public ImageSourceInt(ImageIcon source){ 
    if (source == null) { 
     this.canvasData = new int[0]; 
     return; 
    } 
    this.width = source.getIconWidth(); 
    this.height = source.getIconHeight(); 
    this.scanSize = source.getIconWidth(); 
    this.lineCount = source.getIconHeight(); 

    this.canvasData = new int[this.width*this.height]; 

    // PixelGrabber(Image img, int x, int y, int w, int h, int[] pix, int 
    // off, int scansize) 
    PixelGrabber grabber = new PixelGrabber(source.getImage(), 0, 
      0, this.width, this.height, this.canvasData, 0, this.scanSize); 
    try { 
     grabber.grabPixels(); 
    } catch (InterruptedException e) { 
     e.printStackTrace();// must not be... 
    } 
} 

/** 
* @return a BufferedImage with the data of this ImageSource (referenced)<br> 
* IMPORTANT: if the size changed, the BufferedImage will get invalid, causing strange effects or exceptions 
*/ 
public BufferedImage getReferenceImage(){ 
    DataBuffer buf = new DataBufferInt(this.canvasData, this.canvasData.length); 
    WritableRaster wRaster = Raster.createPackedRaster(buf, this.getWidth(), this.getHeight(), this.getScanSize(), 
      new int[]{0x00FF0000, 0x0000FF00, 0x000000FF, 0xFF000000}, new Point()); 
    BufferedImage bi = new BufferedImage(ColorModel.getRGBdefault(), wRaster, false, null); 
    return bi; 
} 

}