这个JavaBitShift做什么?
我在on-Rosetta代码中发现了一些位移位代码,我大致了解代码的功能,但这部分除外:这个JavaBitShift做什么?,java,bit-shift,Java,Bit Shift,我在on-Rosetta代码中发现了一些位移位代码,我大致了解代码的功能,但这部分除外: rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11); 我认为它需要所有3个像素的平均值,这至少是我输出结果时的样子。但是这是如何工作的呢?这些神奇的数字是什么
rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);
我认为它需要所有3个像素的平均值,这至少是我输出结果时的样子。但是这是如何工作的呢?这些神奇的数字是什么
使用此函数的方法,为了方便粘贴:
公共静态ArrayData getArrayDataFromImage(字符串文件名)引发IOException
{
BufferedImage inputImage=ImageIO.read(新文件(文件名));
int width=inputImage.getWidth();
int height=inputImage.getHeight();
int[]rgbData=inputImage.getRGB(0,0,宽度,高度,null,0,宽度);
ArrayData ArrayData=新的ArrayData(宽度、高度);
//读取图像时翻转y轴
对于(int y=0;y>16)*0.30+((rgbValue&0xFF00)>>8)*0.59+(rgbValue&0xFF)*0.11);
数组数据集(x,高度-1-y,RGB值);
}
}
返回数组数据;
}
这就是使用系数
0.3
、0.59
和0.11
将24位RGB值转换为灰度值的技巧(请注意,这些值加起来等于1
)
此操作(rgbValue&0xFF0000)>>16
剪切位17..24,并将其右移到位置0..7,产生一个介于0和255之间的值(包括0和255)。类似地,(rgbValue&0xFF00)>>8
剪切位8..16,并将其移位到位置0..7
讨论系数,并讨论其他替代方案。唯一需要注意的是,此公式中的整数截断会产生轻微偏差,使图片稍微比需要的颜色暗一些。可能最好做
rgbValue=(int)Math.round((rgbValue&0xFF0000)>>16)*0.30+((rgbValue&0xFF00)>>8)*0.59+(rgbValue&0xFF)*0.11)代码>
public static ArrayData getArrayDataFromImage(String filename) throws IOException
{
BufferedImage inputImage = ImageIO.read(new File(filename));
int width = inputImage.getWidth();
int height = inputImage.getHeight();
int[] rgbData = inputImage.getRGB(0, 0, width, height, null, 0, width);
ArrayData arrayData = new ArrayData(width, height);
// Flip y axis when reading image
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int rgbValue = rgbData[y * width + x];
// What does this do?
rgbValue = (int)(((rgbValue & 0xFF0000) >>> 16) * 0.30 + ((rgbValue & 0xFF00) >>> 8) * 0.59 + (rgbValue & 0xFF) * 0.11);
arrayData.set(x, height - 1 - y, rgbValue);
}
}
return arrayData;
}