I have used the method ImageIO.read(File file);
to read a PNG image file. However, when I use the getRGB(int x, int y)
method on it to extract the alpha it always returns 255 whether the pixel is transparent or not. How do I remedy this inconvenience?
问问题
394 次
2 回答
3
将打包int
颜色转换为Color
对象时,您需要告诉它是否应该计算 alpha 值。
new Color(image.getRGB(x, y), true).getAlpha();
查看Color(int, boolean)
更多详情
于 2013-10-18T01:37:35.187 回答
0
只是想指出,使用 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;
}
于 2013-10-18T09:47:00.170 回答