2010-04-11 138 views

回答

69

Java的Color類可以做轉換:

Color c = new Color(image.getRGB()); 
int red = c.getRed(); 
int green = c.getGreen(); 
int blue = c.getBlue(); 
+0

爲圖像的每個像素創建一個新的Color實例會產生大量垃圾,並且效率非常低。如果您打算處理圖像的每個像素,使用'bufferedImage.getRGB(x,y)'獲得每個像素的RGB顏色效率更高,並按照答案中的描述提取紅色,綠色和藍色分量由JoãoSilva提供。 – Marco13 2017-12-12 15:36:11

7

你需要一些基本的二進制算術它分裂:

int blue = rgb & 0xFF; 
int green = (rgb >> 8) & 0xFF; 
int red = (rgb >> 16) & 0xFF; 

(也可能是其他的全面,老實說,我不記得,文檔也沒有給我一個即時答案)

+0

我相信你是對的。 – HyperNeutrino 2015-07-05 21:19:30

105

一個像素由一個4字節(32位)整數表示,如下所示:

00000000 00000000 00000000 11111111 
^ Alpha ^Red  ^Green ^Blue 

因此,要獲得各個顏色成分,你只需要一個位二進制算術:

int rgb = getRGB(...); 
int red = (rgb >> 16) & 0x000000FF; 
int green = (rgb >>8) & 0x000000FF; 
int blue = (rgb) & 0x000000FF; 

這確實是什麼java.awt.Color類的方法做:

553  /** 
    554  * Returns the red component in the range 0-255 in the default sRGB 
    555  * space. 
    556  * @return the red component. 
    557  * @see #getRGB 
    558  */ 
    559  public int getRed() { 
    560   return (getRGB() >> 16) & 0xFF; 
    561  } 
    562 
    563  /** 
    564  * Returns the green component in the range 0-255 in the default sRGB 
    565  * space. 
    566  * @return the green component. 
    567  * @see #getRGB 
    568  */ 
    569  public int getGreen() { 
    570   return (getRGB() >> 8) & 0xFF; 
    571  } 
    572 
    573  /** 
    574  * Returns the blue component in the range 0-255 in the default sRGB 
    575  * space. 
    576  * @return the blue component. 
    577  * @see #getRGB 
    578  */ 
    579  public int getBlue() { 
    580   return (getRGB() >> 0) & 0xFF; 
    581  } 
6

對於簡單顏色操作,你可以使用

bufImg.getRaster().getPixel(x,y,outputChannels) 

outputChannels是一個用於存儲獲取像素的數組。它的長度取決於圖像的實際通道數。例如,RGB圖像有3個通道; RGBA圖像有4個通道。

該方法有3種輸出類型:int,float和double。 要獲取顏色值範圍從0到255,您的實際參數outputChannels應該是一個int []數組。

相關問題