我有一个疑问。在Android中从Bitmap
获取像素时,我得到了一张图像,这是一张灰度图像。如果我使用getPixels()
并检查值,我可以看到R != G != B的值。
我认为,如果三个滑块(R、G和B)的值相同,则可以检查它是否为灰度图像,但这似乎不可能。有没有一种方法来验证它?
非常感谢!
我有一个疑问。在Android中从Bitmap
获取像素时,我得到了一张图像,这是一张灰度图像。如果我使用getPixels()
并检查值,我可以看到R != G != B的值。
我认为,如果三个滑块(R、G和B)的值相同,则可以检查它是否为灰度图像,但这似乎不可能。有没有一种方法来验证它?
非常感谢!
首先,有几种方法可以实现这个目标。
我建议使用以下方式获取图像的大小(类似于)
int myHeight = myImage.getHeight();
int myWidth = myImage.getWidth();
在这种情况下,我会建议您验证位图的配置,因为它可能是三种不同的格式之一。
ALPHA_8, ARGB_8888, or RGB_565
您可以使用以下方法获取配置:
myImage.getConfig()
例行程序。稍后我们将介绍如何使用它。
现在您已经知道图像的大小,应该运行以下双重循环结构:
boolean isGrayscaleImage = true; // assume it is grayscale until proven otherwise
for(int i = 0; i < myWidth; i++){
for(int j = 0; j < myHeight; j++){
int currPixel = myImage.getPixel(i, j);
if( false == isGrayScalePixel(currPixel) ){
isGrayscaleImage = false;
break;
}
}
}
boolean isGrayScalePixel(int pixel){
int alpha = (pixel && 0xFF000000) >> 24;
int red = (pixel && 0x00FF0000) >> 16;
int green = (pixel && 0x0000FF00) >> 8;
int blue = (pixel && 0x000000FF);
if( 0 == alpha && red == green && green == blue ) return true;
else return false;
}
有一些优化可以进行,但我正在尝试为您记录主要算法。
希望这能帮助您 :-)
int alpha = (pixel & 0xFF000000) >> 24;
int red = (pixel & 0x00FF0000) >> 16;
int green = (pixel & 0x0000FF00) >> 8;
int blue = (pixel & 0x000000FF);
Colors.red()
、Colors.green()
或Colors.blue()
进行检查。
以下是实际代码的一小部分。
for(int x=0;x< bmp.getWidth();x++) {
for(int y=0;y< bmp.getHeight();y++) {
int pixel=bmp.getPixel(x,y);
int alpha=Color.alpha(pixel);
int gray_color=Color.red(pixel);
int gray_color1=Color.green(pixel);
//int gray_color=pixel&0x000000ff;
//int gray_color1=(pixel&0x0000ff00)>>8;
//int gray_color2=(pixel&0x00ff0000)>>16;
//int gray_color3=Math.abs((pixel&0xff000000))>>24;
int pixels= (int)Math.pow(gray_color,gamma);
k.add(""+alpha+" "+gray_color+" "+gray_color1);
bmp.setPixel(x,y,Color.argb(alpha,pixels,pixels,pixels));
}
}
decodeFile()
函数,并将options.preferredConfig
参数设置为ARGB_8888
。这样每个人都可以获得相同比例的正确值。 - SamuSan