[英]Java BufferedImage Not Registering Transparent Pixels?
我已經使用方法ImageIO.read(File file);
讀取PNG圖像文件。 但是,當我在其上使用getRGB(int x, int y)
方法提取Alpha時,無論像素是否透明,它總是返回255。 我該如何解決這種不便?
將打包的int
顏色轉換為Color
對象時,需要告訴它是否應該計算alpha值。
new Color(image.getRGB(x, y), true).getAlpha();
有關更多詳細信息Color(int, boolean)
請參見Color(int, boolean)
只是想指出,使用方法getRGB(x,y)效率極低。 如果要獲取圖像的像素,可以從每個像素提取顏色,然后將像素存儲在一個int數組中。 也要感謝mota解釋為什么這效率低下, 請參閱他的文章 。 下面的例子:
/**===============================================================================================
* Method that extracts pixel data from an image
* @return a 2d array representing the pixels of the image
=================================================================================================*/
public static int[][] getImageData(BufferedImage img) {
int height = img.getHeight();
int width = img.getWidth();
final byte[] imgPixels = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
final boolean is_Alpha_Present = img.getAlphaRaster() != null;
int[][] imgArr = new int[height][width];
if (is_Alpha_Present) {
final int pixelLength = 4; //number of bytes used to represent a pixel if alpha value present
for (int pixel = 0, row = 0, col = 0; pixel < imgPixels.length; pixel = pixel + pixelLength) {
int argb = 0;
argb += (((int) imgPixels[pixel] & 0xff) << 24); //getting the alpha for the pixel
argb += ((int) imgPixels[pixel + 1] & 0xff); //getting the blue colour
argb += (((int) imgPixels[pixel + 2] & 0xff) << 8); //getting the green colour
argb += (((int) imgPixels[pixel + 3] & 0xff) << 16); //getting the red colour
imgArr[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
else {
final int pixelLength = 3;
for (int pixel = 0, row = 0, col = 0; pixel < imgPixels.length; pixel = pixel + pixelLength) {
int argb = 0;
argb += Integer.MIN_VALUE;
argb += ((int) imgPixels[pixel] & 0xff); //getting the blue colour
argb += (((int) imgPixels[pixel+1] & 0xff) << 8); //getting the green colour
argb += (((int) imgPixels[pixel+2] & 0xff) << 16); //getting the red colour
imgArr[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
return imgArr;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.