[英]bufferedImage.getRGB(x, y) does not yield alpha
我有一個BufferedImage i
,我想從該image
的某個像素中獲取顏色 , 包括alpha值 。 使用x
和y
坐標識別像素。
這是我試過的:
Color c = new Color(i.getRGB(x, y));
出於某種原因,新的顏色對象包含正確的RGB,但alpha會丟失。
我究竟做錯了什么?
提前致謝
您正在使用的單參數Color
構造函數會丟棄Alpha信息。 使用雙參數版本,並為hasalpha
傳入true
:
Color c = new Color(i.getRGB(x, y), true);
相關的Javadoc :
Color(int rgb)
使用指定的組合RGB值創建不透明的sRGB顏色,該值由位16-23中的紅色分量,位8-15中的綠色分量和位0-7中的藍色分量組成。
Color(int rgba, boolean hasalpha)
使用指定的組合RGBA值創建sRGB顏色,該值由位24-31中的alpha分量,位16-23中的紅色分量,位8-15中的綠色分量和位0-7中的藍色分量組成。
阿爾法不會丟失。
您必須使用(int,boolean)構造函數,該構造函數獲取像素信息並指定它是否具有帶布爾值的alpha值或帶有4個值的構造函數,紅色,綠色,藍色和Alpha。
來自JavaDoc的(int,int,int,int)構造函數信息
要縮短代碼,您始終可以使用Color color = new Color(i.getRGB(x, y), true);
替換以下所有代碼Color color = new Color(i.getRGB(x, y), true);
它告訴顏色構造函數像素信息確實包含Alpha值。
來自JavaDoc的(int,boolean)構造函數信息
請注意,有時在檢索alpha時,以下方式可能會返回-1,在這種情況下,這意味着它會循環回255,因此您必須執行256-1才能獲得實際的alpha值。 此片段演示了如何加載圖像並在某些坐標上獲取該圖像的顏色,在本例中為0,0。 以下示例可以向您展示如何檢索包括alpha在內的每個顏色值,並將其重建為新的Color。
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
public class main {
public static void main(String [] args){
BufferedImage image = null;
try {
image = ImageIO.read(new URL("image.png"));
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int pixel = image.getRGB(0, 0);
int alpha = (pixel >> 24) & 0xff;
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel >> 0) & 0xff;
Color color1 = new Color(red, green, blue, alpha);
//Or use
Color color2 = new Color(image .getRGB(0, 0), true);
}
}
BufferedImages getRGB(int,int) JavaDoc正如你所看到的那樣:
Returns an integer pixel in the default RGB color model (TYPE_INT_ARGB) and default sRGB colorspace. Color conversion takes place if this default model does not match the image ColorModel. There are only 8-bits of precision for each color component in the returned data when using this method.
這意味着還會檢索Alpha值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.